Scons常用总结

https://blog.csdn.net/MOU_IT/article/details/95229790

https://www.scons.org/doc/production/HTML/scons-user.html#idp105549032622280


common_sources = ['test.c']
src_files = Split("""test.c
                     test.c""")
Program('test', ['test.c', 'test.c'])
Program('test', Glob('*.c', exclude=["os_*_specific_*.cpp"]) + + Glob("os_%s_specific_*.cpp" % currentOS))
Program('test', common_sources + 'test.c')
Program('test', src_files)
Library('test', ['test.c'])
Program('test.c', LIBS=['test'], LIBPATH='.')
Program('test.c', LIBS='test', LIBPATH=['.', '/usr/lib'])
Program('test.c', CPPPATH=['include','/usr/include'])
Object('test.c'. CCFLAGS='-DHELLO')     //生成.o
Program(['test.o', 'test.o'])
objlst = Object('test.c'. CCFLAGS='-DHELLO')
Program('test.c', LINKFLAGS = str(objlst[0]))
programlst = Program(objlst)
print("The program file is: %s"%programlst[0])
Default(programlst)

test_c = File('test.c')
dirs = Dir('test')
fileOrDir = Entry('xyz')
path = "#/include"  #顶层相对路径

import os.path
program_list = Program('test.c')
program_name = str(program_list[0])
if not os.path.exists(program_name)
    print("%s not exist!"%program_name)

env = Environment(VAR="value")
n=File('test.c')
print(env.GetBuildPath([n, 'sub/dir/$VAR']))    #构建位置
env.Install("install", "test.txt")              #scons install
env.Alias('install', '/usr/bin')
env.Install('/usr/bin', hello)
env.InstallAs('/usr/bin/hello-new', hello)
env.InstallAs(['/usr/bin/hello-new',
               '/usr/bin/goodbye-new'],
               [hello, goodbye])
foo =  env.SharedLibrary(target="foo", source="foo.c", SHLIBVERSION="1.2.3")
env.InstallVersionedLib(target="lib", source=foo)
               
Decider('timestamp-newer')  #通过时间戳判断文件是否改变,还有make,timestamp-match,content-timestamp
def decide_if_changed(dependency, target, prev_ni, repo_node=None):
    if dependency.get_timestamp() != prev_ni.timestamp:
        dep = str(dependency)
        tgt = str(target)
        if specific_part_of_file_has_changed(dep, tgt):
            return True
    return False
Decider(decide_if_changed)
env1 = Environment(CPPPATH = ['.'])
env2 = env1.Clone()
env2.Decider('timestamp-match')
env1.Program('prog-content', 'program1.c')
env2.Program('prog-timestamp', 'program2.c')

Depends(test, programlst)
hello_obj = Object('hello.c', CCFLAGS='-MD -MF hello.d', CPPPATH='.')
SideEffect('hello.d', hello_obj)        #relevant targets executed sequentially, not in parallel
ParseDepends('hello.d')     #头文件依赖解析
Ignore(hello_obj, 'hello.h')
Ignore('.', [hello_obj])

AlwaysBuild(hello)

import os
os.environ["LIB_DIR"]='usr/bin'  #全局库输出路径,跨script文件
print("Shell is", os.environ['SHELL'])
env = Environment(CC='gcc', CCFLAGS='-O2')
env.Program('test.c')
print("CC is: %s" % env['CC'])
print("CC is: %s" % env.subst('$CC'))
print("LATEX is: %s" % env.get('LATEX', None))
env = Environment(FOO='foo', BAR='bar')
cvars = env.Dictionary()
for key in ['OBJSUFFIX', 'LIBSUFFIX', 'PROGSUFFIX']:
    print("key = %s, value = %s" % (key, cvars[key]))
for item in sorted(env.Dictionary().items()):
    print("construction variable = '%s', value = '%s'" % item)
print(env.Dump())
env = Environment(CCFLAGS='-DFOO')
print("CCCOM is: %s" % env['CCCOM'])
AllowSubstExceptions(IndexError, NameError, ZeroDivisionError)
def_env = DefaultEnvironment(tools=['gcc', 'gnulink'], CC='/usr/local/bin/gcc')
def_env['CC'] = '/usr/local/bin/gcc'
def_env.Replace(CCFLAGS='-DDEFINE2')
def_env.Append(CCFLAGS=['LAST'])        #存在继续追加AppendUnique
def_env.Prepend(CPPDEFINES=['FIRST'])   #PrependUnique
def_env.SetDefault(SPECIAL_FLAG='-extra-option')    #只有值
env.SharedLibrary(
    target='word',
    source='word.cpp',
    SHLIBVERSION="1.2.3",
    SHLIBSUFFIX='.ocx',
    LIBSUFFIXES=['.ocx'],
)                                                   #生成动态库
env.Program('hello', 'hello.c', parse_flags='-Iinclude -DEBUG -lm')
path = ['/usr/local/bin', '/bin', '/usr/bin']
path = os.environ['PATH']
env = Environment(ENV={'PATH': path})
env = Environment(ENV=os.environ.copy())
env.PrependENVPath('PATH', '/usr/local/bin')
env.AppendENVPath('LIB', '/usr/local/lib')
flags = {'CCFLAGS': '-whatever -O3'}
env.MergeFlags(flags)
env.MergeFlags('-whatever -I/usr/opt/include -O3 -I/usr/local/include')
env = Environment(CCCOMSTR = "Compiling $TARGET",
                  LINKCOMSTR = "Linking $TARGET")       #打印编译与构建命令
if ARGUMENTS.get('VERBOSE') != '1':
    env['CCCOMSTR'] = "Compiling $TARGET"
    env['LINKCOMSTR'] = "Linking $TARGET"
lib = env.Program('foo.c')
env.Precious(lib)       #构建过程中防止删除 
env.NoClean(lib)        #清除过程中防止删除

Progress('Evaluating $TARGET\n')

import atexit
def print_build_failures():
    from SCons.Script import GetBuildFailures
    for bf in GetBuildFailures():
        print("%s failed: %s" % (bf.node, bf.errstr))       #Detailed Build Status
atexit.register(print_build_failures)

if not GetOption('help'):
    SConscript('src/SConscript', export='env')  #sub scons

import os
num_cpu = int(os.environ.get('NUM_CPU', 2))
SetOption('num_jobs', num_cpu)
print("running with -j %s" % GetOption('num_jobs'))     #并发执行

SetOption('random', 1)
SetOption('experimental', 'ninja')
AddOption(
    '--prefix',
    dest='prefix',
    type='string',
    nargs=1,
    action='store',
    metavar='DIR',
    help='installation prefix',
)
env = Environment(PREFIX=GetOption('prefix'))           
installed_foo = env.Install('$PREFIX/usr/bin', 'foo.in')
Default(installed_foo)

vars = Variables(None, ARGUMENTS)
vars.Add('RELEASE', help='Set to 1 to build for release', default=0)
env = Environment(variables=vars)
Help(vars.GenerateHelpText(env))

cppdefines = []
for key, value in ARGLIST:
    if key == 'define':
        cppdefines.append(value)
env = Environment(CPPDEFINES=cppdefines)

Command(
    "file.out",
    "file.in",
    action=[
        Delete("tempdir"),
        Mkdir("tempdir"),
        Copy("tempdir/${SOURCE.file}", "$SOURCE"),
        "process tempdir",
        Touch("$TARGET"),   #更新文件
        "process tempdir",
        Move("$TARGET", "tempdir/output_file"),
        Delete("tempdir"),
        Chmod("$TARGET", 0o755),
    ],
)
t = Command('foo.out', 'foo.in', 'build -o $TARGET $SOURCE')
Clean(t, 'foo.log')

VariantDir('build', 'src', duplicate=False)      #指定src目录编译输出要创建到build下面
SConscriptChdir(True)   #进入子目录,改变目录
SConscript('src/SConscript', variant_dir='build', duplicate=False)
SConscript(
    [
        'drivers/display/SConscript',
    ], 
    exports='env'
)
Export(args)
Import('env')   #变量跨script导出导入,‘*’代表导入所有
Return('obj')   #调用script返回
import dbm.gnu
SConsignFile(dbm_module=dbm.gnu)

objs = []
for subdir in ['foo', 'bar']:
    o = SConscript('%s/SConscript' % subdir)
    objs.append(o)
env.Library('prog', objs)

Repository('/usr/repository1', '/usr/repository2')  #添加编译查找目录或script文件,优先级较高

conf = Configure(env)
if not conf.CheckCHeader('math.h'):
    print('Math.h must be installed!')
    Exit(1)
if conf.CheckCHeader('foo.h'):      #CheckFunc('strcpy') CheckLib('m') CheckLibWithHeader('m', 'math.h', language='c') CheckType('off_t', '#include <sys/types.h>\n)必须包含头文件
CheckTypeSize('unsigned int')   CheckProg('foobar'):
    conf.env.Append(CPPDEFINES='HAS_FOO_H')
env = conf.Finish()
conf = Configure(env, , custom_tests={'CheckMyLibrary': CheckMyLibrary})    #自定义CheckMyLibrary
def CheckMyLibrary(context):
    context.Message('Checking for MyLibrary...')
    result = context.TryLink(mylib_test_source_file, '.c')
    context.Result(result)
    return result
if not conf.CheckMyLibrary():

CacheDir('/usr/local/build_cache')
NoCache('hello.o')
LAUNCHDIR = GetLaunchDir() #执行scons目录

env = Environment(COMPILATIONDB_USE_ABSPATH=True)   #compile_commands.json
env.Tool('compilation_db')   #ninja
cdb = env.CompilationDatabase('compile_database.json')
Alias('cdb', cdb)

scons -c VERBOSE=1 -Q -j32 COLOR=magenta  --tree=prune,all,linedraw,status,derived --debug=explain,presub,findlibs,stacktrace,prepare,duplicate  --warn=target-not-built --implicit-cache --cache-show --cache-disable --cache-force --random --implicit-deps-changed --implicit-deps-unchanged -n --experimental=ninja --compilers=mingw --taskmastertrace=- prog --prefix=/tmp/install test -Y /usr/repository1

Help("""
Type: 'scons program' to build the production program,
      'scons debug' to build the debug version.
""", append=True)
if env['PLATFORM'] == 'win32':
    Help("\nType: 'scons windebug' to build the Windows debug version.\n")
if 'bar' in COMMAND_LINE_TARGETS:
    print("Don't forget to copy `bar' to the archive!")
if Execute(Mkdir('/tmp/my_temp_directory')):
    # A problem occurred while making the temp directory.
    Exit(1)
platform = ARGUMENTS.get('OS', Platform())          #scons -Q OS=linux
for platform in ['newell', 'post']:
    SConscript('src/SConscript', variant_dir='build/' + platform)
EnsurePythonVersion(2, 5)
EnsureSConsVersion(1, 0)
print(env.Dump())
GetDepend(macro)

scons -h
scons --target=vs2012 -s —verbose
python -m pip install ninja


创作不易,小小的支持一下吧!

相关推荐

  1. TS总结

    2024-05-16 06:50:11       31 阅读
  2. vim键位总结

    2024-05-16 06:50:11       34 阅读
  3. Docker命令总结

    2024-05-16 06:50:11       44 阅读
  4. 前端框架总结

    2024-05-16 06:50:11       37 阅读
  5. Linux命令总结

    2024-05-16 06:50:11       36 阅读
  6. Linux个人总结

    2024-05-16 06:50:11       40 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-16 06:50:11       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-16 06:50:11       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-16 06:50:11       20 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-16 06:50:11       20 阅读

热门阅读

  1. linux编译gdb

    2024-05-16 06:50:11       15 阅读
  2. springboot集成dubbo实现微服务系统

    2024-05-16 06:50:11       14 阅读
  3. 31、Flink 的 DataStream API 数据流算子详解

    2024-05-16 06:50:11       17 阅读
  4. 排序算法面试专用

    2024-05-16 06:50:11       13 阅读
  5. 视觉识别应用的场景有哪些

    2024-05-16 06:50:11       14 阅读
  6. LeetCode 257. 二叉树的所有路径

    2024-05-16 06:50:11       16 阅读
  7. C#知识|上位机面向对象编程时如何确定类?

    2024-05-16 06:50:11       15 阅读