views:

85

answers:

1

Where am I going wrong; I want to define a preprocessor value on the command-line for g++ but it fails. Below is sample code that replicate my problem:

[edit] I'm using:
g++ (Debian 4.3.2-1.1) 4.3.2
GNU Make 3.81

test.h

#ifndef _test_h_
#define _test_h_

#include "iostream"

#if defined(MY_DEFINED_VALUE)
#if (MY_DEFINED_VALUE != 5)
#undef MY_DEFINED_VALUE
#define MY_DEFINED_VALUE 3
#endif //(MY_DEFINED_VALUE != 5)
#else //defined(MY_DEFINED_VALUE)
#error  Error - MY_DEFINED_VALUE is not defined
#endif //defined(MY_DEFINED_VALUE)

class test
{
public:
 int val;
 test() {}
 void show() { std::cout << "val = " << val << "\n"; }
};

#endif //_test_h_

test.cpp

 //#define MY_DEFINED_VALUE 5
 #include "test.h"

 int main()
 {
  test t;
  t.val = MY_DEFINED_VALUE;
  t.show();
  return 0;
 }

Makefile

#=====
CC = g++
LD = g++
USERDEFINES = -DMY_DEFINED_VALUE
CFLAGS = -Wall
LDFLAGS = 
RM = /bin/rm -f
SRCS = test.cpp
OBJS = test.o
PROG = test
#=====
$(PROG): $(OBJS)
 $(LD) $(LDFLAGS) $(OBJS) -o $(PROG)
#=====
%.o: %.c
 $(CC) $(USERDEFINES) $(CFLAGS) -c $<
#=====
clean:
 $(RM) $(PROG) $(OBJS)

If I uncomment the #define in test.cpp, all is well (prints 5). If I comment it I get the #error.

+3  A: 

The problem is in your Makefile. The %.o: %.c rule doesn't match a .cpp file, so GNU Make's built-in %.o: %.cpp rule is being triggered instead.

If you change %.o: %.c to %.o: %.cpp, it'll run fine.

Jander
slashmais
Yeah, little things like that are the most annoying. It happens to the best of us. The only reason I noticed it was I added an "echo" just before the call to $(CC), then was confused when the echo didn't show up in the output.
Jander
Upshot of it is: I now know a lot more about C++ preprocessor commands than I did before this little hiccup ;)
slashmais