Passing a Makefile parameter to change compiled code

I'm new at this. I am working on a common C ++ library, and I want it to be able to compile with or without support for a specific function (code block). In other words, how do I let the user choose whether to compile the library with this function by (possibly) passing a parameter to the make command?

For example, I need the user to be able to do this:

make --with-feature-x 

How should I do it? Do I need to write a configuration file, for example? Or can I do this directly in my Makefile?

+4
source share
1 answer

I believe the next way should work. You define an environment variable when you run make . In the Makefile, you check the status of an environment variable. Depending on the state, you define the parameters that will be passed to g ++ when compiling the code. g ++ Uses the parameters in the preprocessing phase to decide what to include in the file (for example, source.cpp).

Team

 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 to or not (like any value):

 ifdef FEATURE #do something based on it else # feature is not defined. Maybe set it to default value FEATURE=0 endif 
+9
source

Source: https://habr.com/ru/post/1495046/


All Articles