I would like to have a global way to do something like this

#ifdef GRAPHICS
//do some stuff that relies on graphics libraries that may or may not be installed
#endif

The problem with defines is that they have to be defined in every file, or at least be defined in a header that is included in every file that I wish to do this.

What I'm looking for is more of maybe a compiler option or something? Where I can say

g++ MyProgram +GRAPHICS
or
g++ MyProgram -GRAPHICS

And it will just ignore parts of the code completely if GRAPHICS is not specified.

Sorry if this is unclear, but I'll explain as we go! haha

Thanks,
Dave

That is typically something handled by the build process.

If you want to have the #defines in every file, you can specify the flag, or not, in your Makefile(s).

Here's an example makefile that builds a program "foo" from the following files:
foo.cpp
baz.h
baz.cpp
quux.h
quux.cpp

If compiling on Windows, it will automatically #define GRAPHICS for every source file and link the executable with the Windows GDI library.

#----------------------------------------
# Common stuff
#
CC     = g++
CFLAGS = -Wall
LFLAGS = 

#----------------------------------------
# Windows-specific nonsense
#
Windows = $(if $(COMSPEC)$(ComSpec),1,)

ifeq ($(Windows),1)
CFLAGS = $(CFLAGS) -DGRAPHICS
LFLAGS = $(LFLAGS) -lgdi32
endif

#----------------------------------------
# Main target rule
#
foo: foo.o baz.o quux.o
	$(CC) -o foo $^ $(LFLAGS)

#----------------------------------------
# Individual object files rule
#
%.o: %.cpp %.h
	$(CC) $(CFLAGS) -c $<

Another common option is to have a file (often named something like "machine.cpp") for each type of architecture that actually implements the OS-dependant code, and a common "machine.h" file which prototypes the routines implemented by the machine files. That way your program can use the machine.h API to do OS-dependant stuff. And again, the build system will compile and link with the appropriate version of the "machine.cpp" file.

Hope this helps get you going.

ah great! so

g++ -DGRAPHICS

is the same as having all the files being compiled having a #define GRAPHICS 1 ?

so then I could even use
if(GRAPHICS)

instead of
#ifdef GRAPHICS

?

Thanks,

Dave

No, it is the same as all the files having a #define GRAPHICS To have a value: g++ -DGRAPHICS=1 --> #define GRAPHICS 1 if (GRAPHICS) will work if and only if GRAPHICS is always defined to have some value (such as 0 or 1). That is typically a wasteful way to do it though, because you add time used and space occupied for every test. It is best to stick with the #ifdef GRAPHICS so that only the code you need gets compiled into the executable.

[edit]
You can still test for different values though:

#if GRAPHICS == 1
  do_x();
#elif GRAPHICS == 2
  do_y();
#else
  do_z();
#endif

Hope this helps.

Comments
Both good answers.
This article has been dead for over six months. Start a new discussion instead.