Search code examples
iosxcodestatic-linking

Conditional link static library in XCode with environment variable


I want to link a static library (.a file) into my code with some restrictions

  • The condition should be an environment variable instead of build type (Debug, Release) or architecture.
  • If the static library is not used (not imported, not used in the code), then the final binary shouldn't contain any references to it at all.

The code should look like:

#ifdef CRASH_LOGGING
[Crittercism enableWithAppID:@"abc"]
#endif

And the environment variable should have a similar name.

I played with OTHER_LINKER_FLAGS = -weak_library, removing the .a from the target, setting it as optional, but I can't get it to work. Either the library is not linked, I get a compile error, or part the .a belongs to the final executable.

How can I achieve this?


Solution

  • In the end I ended up solving this problem by adding more parameters to the xcodebuild command line.

    Basically what you need to do is to adjust:

    • Where the header .h files are located
    • Where the library .a is located
    • Tell the linker that you want to use the library -lCrittercism_v4_0_7
    /usr/bin/xcodebuild -configuration Release clean
    "LIBRARY_SEARCH_PATHS=\${LIBRARY_SEARCH_PATHS} \${PROJECT_DIR}/Libraries/CrittercismSDK"
    "HEADER_SEARCH_PATHS=\${HEADER_SEARCH_PATHS} \${PROJECT_DIR}/Libraries/CrittercismSDK" 
    "OTHER_LDFLAGS=-lCrittercism_v4_0_7"
    

    With this approach you don't need to add the library to the target or to Xcode at all. If the last three parameters aren't added to the command line, the library won't belong to the final executable at all.