Who defined my name first? Turnabout is fair play

Raymond Chen

You’re trying to compile your program and you’re getting an error complaining that somebody already has a conflicting definition for a macro or some other name you’re using.

error: sample.cpp(35): conflicting definition of macro 'AWESOME'
error: sample.cpp(92): conflicting definition of type 'AWESOME'

If your compiler is helpful, it’ll tell you where the previous definition was. But what if your compiler isn’t quite so helpful? How can you find that conflicting definition?

Turnabout is fair play.

(I don’t actually believe that turnabout is fair play, but it makes for a catchy title.)

The problem is that you’re the second definition and you want to find the first definition. So jump to the head of the line and become the new first definition. Compile the file with the -DAWESOME=@ command line switch. This tells the compiler to act as if the line #define AWESOME @ were at the top of the file.

When the offending line is reached, the line that defines the AWESOME macro or declares a type named AWESOME or otherwise uses the word AWESOME, you’ll get a compiler error. If it’s a conflicting macro definition, you’ll get something like

error: header.h(10): conflicting definition of macro 'AWESOME'

when the first definition is reached. With your addition of the -D, it’s now the second definition, and therefore its definition conflicts with yours. Similarly, if it’s a conflicting type name, you’ll get something like

error: header.h(30): illegal character @ in source file

when the conflicting type definition is reached. This time, instead of a conflicting macro definition, you created a syntax error.

On the other hand, if somebody #undefs your symbol before redefining it, then the -D trick won’t work.

As I noted, if your compiler is friendly and helpful, you won’t need to use this tip, but sometimes you have to make do with what you’ve got.


Discussion is closed.

Feedback usabilla icon