5

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?

yelsayed
  • 5,236
  • 3
  • 27
  • 38

1 Answers1

12

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
maditya
  • 8,626
  • 2
  • 28
  • 28
  • Perfect! Thanks a lot. Could you also tell me how to check if FEATURE is defined/passed in the first place? – yelsayed Aug 03 '13 at 00:08
  • The make `ifeq` syntax above is wrong. It should be `ifeq ($(FEATURE),1)` instead. As for your question, you'll need give more details. I'm not sure about maditya, but I can't understand what you mean by _how to check if FEATURE is defined/passed in the first place_. – MadScientist Aug 03 '13 at 00:29
  • 1
    @MadScientist You're right, I wrote that from memory and messed it up. Will fix. Also I think OP is asking to see whether the variable is set (to any value), for which an `ifdef` ought to work I think – maditya Aug 03 '13 at 00:54
  • @maditya That's what I had in mind, I had experimented with ifdef and failed but now I got it. – yelsayed Aug 03 '13 at 01:25