加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在c文件的#ifdef中使用makefile中的变量

发布时间:2020-12-16 09:57:57 所属栏目:百科 来源:网络整理
导读:Makefile ifeq ($(wifiSim),1)WIFISIM :=1endifall: test.cpptest.cpp : test.o ./a.outtest.o : c++ test.cpp test.cpp #include iostreamusing namespace std;int main(){ #ifdef WIFISIM cout "Inside wifisim = 1" endl; #else cout "Outside wifisim =

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读