简体   繁体   中英

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.

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.

Your Makefile can determine the hostname and set the specific vars with -D for your build:

Example:

HOSTNAME=$(shell hostname)

ifeq ($(HOSTNAME), localhost1.localdomain)
    ANY_VAR=COMPILE_VERSION_1
else
    ANY_VAR=COMPILE_VERSION_2
endif

$(info $(HOSTNAME))
$(info $(ANY_VAR))

%.o: %.cpp
    g++ -D$(ANY_VAR) $< -c

OBJECTS=main.o

go: $(OBJECTS)
    g++ $^ -o go

clean:
    rm -f *.o
    rm -f go

Your C/C++ can use this vars with something like that:

#include <iostream>

#ifdef COMPILE_VERSION_1
std::string x="Version1";
#endif

#ifdef COMPILE_VERSION_2
std::string x="Version2";
#endif

int main()
{   
    std::cout << x << std::endl;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM