Reputation: 1290
I have 3 files:
main.c
#include <stdio.h>
#include <stdlib.h>
#include "test.h"
#define DEBUG
int main()
{
testFunction();
return 0;
}
test.h
#ifndef TEST_H
#define TEST_H
#include <stdio.h>
#include <stdlib.h>
void testFunction();
#endif // TEST_H_INCLUDED
test.c
#include "test.h"
void testFunction(){
#ifdef DEBUG
printf("I'm inside the testFunction\n");
#endif
}
THE QUESTION: Why does the program not print stuff in #ifdef DEBUG block? If I write #define DEBUG in test.h or test.c everything is fine. What's the problem then #define DEBUG in main.c? Thanks.
Upvotes: 7
Views: 11338
Reputation:
Preprocessor directives define and ifdef do not work as I imagined?
No, not quite. You seem to believe that preprocessor directives traverse file boundaries, which they don't. The scope of a #define
d preprocessor macro is only the single file it's defined in, or other files only if those other files #include
the file containing the macro definition.
Perhaps it would help to imagine that you run the compiler (and thus the preprocessor) on each file separately (which you do, even if you don't realize it). There's no way the preprocessor could tell DEBUG
has been defined in a file which it doesn't operate on.
Upvotes: 15
Reputation: 17732
Because DEBUG
is #define
'd in main.c
, it is not visible in test.c
. You need to #define
it in the build settings, or in a header
Upvotes: 3
Reputation: 133629
Because you defined DEBUG
inside main.c
but test.c
doesn't include main.c
so while compiling the translation unit the preprocessor symbol is not present.
You should declare global scope macros in a header file and then include it where needed.
Upvotes: 2
Reputation: 4380
You define DEBUG in the main.c -- that is not visible to test.c -- if you want DEBUG to be visible to both main.c and test.c, you should define it in test.h
Upvotes: 1