objective-ciphonexcodegcc

How to manually throw a compiler error in GCC and Xcode


In xcode, while compiling apps with gcc, I want to throw compilation time errors if things like NSZombieEnabled is on for a distribution release, thus ensuring that compilation will fail and I won't accidentally do something stupid.

I did some googling, but could not figure out how to cause the compiler to bail if a certain condition is met. Surely it must be easy, am I just not finding it?


Solution

  • Use the #error directive:

    #if SHOULD_FAIL
    #error "bad compiler!"
    #endif
    
    int main()
    {
        return 0;
    }
    
    $ gcc a.c -DSHOULD_FAIL=0 # passes fine
    $ gcc a.c -DSHOULD_FAIL=1
    a.c:2:2: error: #error "bad compiler!"
    

    Since NSZombieEnabled is an environment variable, you'll need to do something clever in your build script to define your macro as zero or one.

    Strictly speaking, the #error directive occurs in the C Preprocessor, not gcc. But that shouldn't matter in the case you've described.