gpt4 book ai didi

c++ - 如何在 C++ 文件中的 #ifdef 中使用 Makefile 中的变量

转载 作者:行者123 更新时间:2023-12-02 14:25:49 25 4
gpt4 key购买 nike

Makefile

ifeq ($(wifiSim),1)
WIFISIM :=1
endif

all: test.cpp

test.cpp : test.o
./a.out

test.o :
c++ test.cpp

test.cpp

#include <iostream>

using namespace std;

int main()
{
#ifdef WIFISIM
cout << "Inside wifisim = 1" << endl;
#else
cout << "Outside wifisim = 1" << endl;
#endif

return 0;
}

我想使用test.cpp中的WIFISIM。我正在运行 make wifiSim=1 all但 else 是在 test.cpp

中执行的

有什么办法可以做到这一点,而不需要对 test.cpp 的编译方式进行任何更改,因为我需要在许多文件中使用此标志 WIFISIM,但我不希望改变它们的编译方式。

最佳答案

你可以这样做

ifeq ($(wifiSim),1)
WIFISIM := -DWIFISIM
endif

all: test.cpp

test.cpp : test.o
./a.out

test.o :
c++ $(WIFISIM) test.cpp

"Is there any way I can do it without doing any changes in the way the compilation for "test.cpp" is done, because I need to use this flag WIFISIM in many files and I do not want to change the way compilation for them is being done."

不,如果不更改规则中的编译器调用操作,就没有办法。

您应该改变编写 makefile 的策略。 make 实际上支持implicit rules如何从 .cpp 创建 .o 文件并使用如下所示的操作

$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c

因此,您可以有条件地将 -DWIFISIM 添加到 $(CPPFLAGS)$(CXXFLAGS) 变量,并且它将被应用对于所有已编译的 .cpp 文件。

使用隐式规则的示例:

ifeq ($(wifiSim),1)
CXXFLAGS += -DWIFISIM
endif

SRC_FILES := test.cpp abc.cpp yxz.cpp
OBJ_FILES := $(patsubst %.cpp,%.o,$(SRC_FILES))

all: test

test: $(OBJ_FILES)

关于c++ - 如何在 C++ 文件中的 #ifdef 中使用 Makefile 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30291476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com