Search code examples
scons

SCons Dynamic Construction Variable


I would like to have a dynamic environmental variable in SCons.

Example: Add -DFILE_NAME=file.c to the build command.

env['FILE_NAME'] = ['${str($TARGET).upper()}']
env.Append(CPPDEFINES={'FILE_NAME': '$FILE_NAME'})

I'm not sure if this is possible but the documentation with _concat, source or the older documentation for CCPDBFLAGS makes it seem like it might be.

Using SCons 3.1.1


Solution

  • This is actually a bug. A workaround is below.

    import hashlib
    
    env = Environment(platform='darwin')
    env['CC'] = 'clang'
    
    # env.Append(CPPDEFINES={'SOURCE': '$SOURCE'})
    # env.Append(CPPDEFINES={'TARGET': '$TARGET'})
    
    def fileHashGenerator(env, target, source):
        print("'%s' '%s' '%s'" % (env, target, source))
        if source:
            print("has source")
    
            fileHash = int(hashlib.sha1(source.path.encode()).hexdigest(), 16) % (10 ** 8)
            print(fileHash)
            h = (fileHash).to_bytes(8, byteorder='big').hex()
            print(h)
            return h
        else:
            print("No target", type(target))
        return 'NOTHING'
    
    env['FILE_HASH'] = '${fileHashGenerator(__env__,TARGET,SOURCE)}'
    
    # env.Append(CPPDEFINES={'FILE_HASH': '$FILE_HASH'})
    env.Append(CPPFLAGS=['-DFILE_HASH=$FILE_HASH'])
    env.Append(CPPFLAGS=['-DFILE_TARGET=${TARGET}'])
    env.Append(CPPFLAGS=['-DFILE_SOURCE=$SOURCE'])
    env['fileHashGenerator'] = fileHashGenerator
    
    env.Program('main', ['main.c'])
    

    Don't use CPPDEFINES, instead append it to CPPFLAGS. Thanks @bdbaddog for the assist in the SCons discord.