简体   繁体   English

C ++,g ++,基于主机名的条件编译?

[英]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. 如果我包含#DEFINE testing_env ,这将很好地工作,但是像这样,我需要在每次切换环境时手动注释/取消注释此定义。

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. 然后,可以在编译行(通常在Makefile中)中使用-DTEST_ENVIRONMENT指定测试环境。 of use of -D option: -D选项的使用:

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: 您的Makefile可以确定主机名,并使用-D为您的构建设置特定的变量:

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: 您的C / C ++可以在以下变量中使用此var:

#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;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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