There is still no way to pass C/C++ compiler flags to only c/c++ files added by 
compile pragma. Related RFC: 
[https://github.com/nim-lang/RFCs/issues/137](https://github.com/nim-lang/RFCs/issues/137)

I found workaround that create static link library from the nim file that only 
has passC and compile pragma so that passC affect to only c/c++ files specified 
in that nim file.

Because of this bug, this code works only in devel Nim. 
[https://github.com/nim-lang/Nim/issues/12745](https://github.com/nim-lang/Nim/issues/12745)

For example:

test.h 
    
    
    int getX();
    
    
    Run

test.c 
    
    
    int getX() {
      return MY_X;
    }
    
    
    Run

testc.nim 
    
    
    # Pass C compiler options only to test.c
    {.passC: "-D MY_X=123".}
    {.compile: "test.c".}
    
    
    Run

testmod.nim 
    
    
    import os, strformat, std/compilesettings
    
    proc getX*(): int {.header: "test.h".}
    
    template linkModule(modulePath, nimCmd = "c", nimOptions: static[string] = 
"") =
      static:
        doAssert nimCmd == "c" or nimCmd == "cpp"
      
      block:
        const
          modName = splitPath(modulePath).tail
          libpath {.inject.} = querySetting(SingleValueSetting.nimcacheDir) / 
modName & ".staticlib"
          modulePath2 {.inject.} = modulePath.quoteShell
          nimCmd2 {.inject.} = nimCmd
          nimOptions2 {.inject.} = nimOptions.string
        
        {.passL: libpath.}
        # `--os:any --gc:arc -d:useMalloc` is used to avoid compiling and 
linking stdlib_io.nim for faster build.
        # It doesn't affect this module.
        const cmd = fmt"{getCurrentCompilerExe()} {nimCmd2} --app:staticlib 
--os:any --gc:arc -d:useMalloc --out:{libpath.quoteShell} {nimOptions2} 
{modulePath2}"
        
        static: echo cmd
        const ret = gorgeEx(cmd)
        static: echo ret.output
        when ret.exitCode != 0:
          {.error: "Abort due to compile error".}
    
    linkModule "testc.nim"
    
    
    Run

sample.nim 
    
    
    import testmod
    
    echo getX()
    
    
    Run

Reply via email to