Passing parameter to Makefile to change compiled code
c++, makefile, shared-libraries
Solution
I believe the following way should work. You define an environment variable when running `make`. In the Makefile, you check the status of the environment variable. Depending on the status, you define the options that will be passed to g++ when compiling the code. g++ Uses the options in the preprocessing phase to decide what to include in the file (e.g. source.cpp).
The command
make FEATURE=1
Makefile
ifeq ($(FEATURE), 1) #at this point, the makefile checks if FEATURE is enabled
OPTS = -DINCLUDE_FEATURE #variable passed to g++
endif
object:
g++ $(OPTS) source.cpp -o executable //OPTS may contain -DINCLUDE_FEATURE
source.cpp
#ifdef INCLUDE_FEATURE
#include feature.h
//functions that get compiled when feature is enabled
void FeatureFunction1() {
//blah
}
void FeatureFunction2() {
//blah
}
#endif
To check if FEATURE is passed in or not (as any value):
ifdef FEATURE
#do something based on it
else
# feature is not defined. Maybe set it to default value
FEATURE=0
endif
Problem
I'm new to make. I am working on a C++ shared library, and I want it to have the option to compile with or without support for a certain feature (block of code). In other words, how do I enable the user to choose whether or not to compile the library with that feature by (maybe) passing a parameter to the make command? For example, I need the user to be able to do this: ``` make --with-feature-x ``` How do I do this? Do I need to write a configure file for example? Or can I do this directly within my Makefile?