How to use variable from makefile in #ifdef file in C ++ file

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

      

I want to use "WIFISIM" in test.cpp. I run "make wifiSim = 1 all" But else is executed in test.cpp

Is it possible to do this without making any changes to the compilation method for "test.cpp", because I need to use this WIFISIM flag in many files and I don't want to change the compilation method for them.

+3


source to share


2 answers


You can do something like this

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

all: test.cpp

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

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

      

"Is there a way to do this without making any changes to the way 'test.cpp' is compiled because I need to use this WIFISIM flag in many files and I don't want to change the way they are compiled for them."

No, there is no way without changing the compiler invocation action in the rule.

You must change your strategy by creating a makefile. make

actually supports implicit rules on how to create a file .o

from .cpp

and uses an action that looks like



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

      

So you can add -DWIFISIM

conditionally to variables $(CPPFLAGS)

or $(CXXFLAGS)

, and it will apply for all compiled files .cpp

.

An example using implicit rules:

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)

      

+7


source


If you are using GCC, you can use the option -DWIFISIM

as parameters passed to GCC / g ++. Other compilers have similar options, for example /D

in Microsoft Visual Studio:

CXXFLAGS = 

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

all: test.cpp

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

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

      



Result:

$ make -n wifiSim=1
c++  -DWIFISIM test.cpp
./a.out
$ make -n
c++  test.cpp
./a.out

      

0


source







All Articles