Search code examples
c++g++c-preprocessorconditional-compilation

C++, g++, conditional compilation based on host name?


I have come across the following problem:

Our testing environment is not able to fully simulate a certain hardware part of the production environment, and therefore some code needs excluding when testing the application.

I therefore need something in the way of

 #IFNDEF testing_env
 //code to exclude
 #ENDIF

This works just fine if i include a #DEFINE testing_env, but like this i need to manually comment/uncomment this define every time i switch environments.

I'm looking for a way to do this based on the host name or a similar feature. I have tried to look for conditional compilation based on environment variables, but apparently this is not possible.


Solution

  • Usually you create a specific build profile for the testing env (dedicated make rules) and another build profile (other make rules) for the other environments.

    Test environment can then be specified with -DTEST_ENVIRONMENT on the compilation line (usually in the Makefile), eg. of use of -D option:

    g++ -DTEST_ENVIRONMENT -o test main.c

    then

    #IFNDEF TEST_ENVIRONMENT
    //code to exclude
    #ENDIF
    

    will work fine.