Search code examples
node-gypgypcflags

Per-source cflags


Is there a way in gyp to enable certain cflags only for some source files?

In the context of this bug I'd like to find a way to have some code compiled with some SSE features enabled, while other code (to detect the availability of said features at runtime and to offer fallbacks) should not make use of those features during optimization.

As so often, I find the node-gyp documentation thoroughly insufficient.


Solution

  • As workaround you can create a static library target in your .GYP file with specific cflags and then to link this static lib against your main target depending on some condition.

    {
       'variables: {
           'use_sse4%': 0, # may be redefined in command line on configuration stage
       },
       'targets: [
           # SSE4 specific target
           {
               'target_name': 'sse4_arch',
               'type': 'static_library',
               'sources': ['sse4_code.cpp'],
               'cflags': ['-msse4.2'],
           },
           # Non SSE4 code
           {
               'target_name': 'generic_arch',
               'type': 'static_library',
               'sources': ['generic_code.cpp'],
           },
           # Your main target
           {
               'target_name': 'main_target',               
               'conditions': [
                   ['use_sse4==1', # conditional dependency on the `use_ss4` variable
                       { 'dependencies': ['sse4_arch'] },   # true branch
                       { 'dependencies': ['generic_arch'] } # false branch
                   ],
               ],
           },  
       ],
    }
    

    More details on dependencies, variables, and conditions are in GYP documentation