Search code examples
c++makefilecompiler-flags

How to use a variable from a Makefile in #ifdef 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 the WIFISIM in the test.cpp. I am running make wifiSim=1 all But the else is being executed in 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.


Solution

  • You may 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 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."

    No, there's no way without changing the compiler call action in the rule.

    You should change your strategy writing the makefile. make actually supports implicit rules how to create a .o file from a .cpp and uses an action that looks like

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

    Thus you could add the -DWIFISIM conditionally to the $(CPPFLAGS) or $(CXXFLAGS) variables, and it will be applied for all .cpp files compiled.

    Sample 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)