user1242967
user1242967

Reputation: 1290

Preprocessor directives define and ifdef do not work as I imagined?

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

Answers (5)

akhil
akhil

Reputation: 732

define DEBUG macro inside the makefile for the global visibility

Upvotes: 0

user529758
user529758

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 #defined 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

Dan F
Dan F

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

Jack
Jack

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

K Scott Piel
K Scott Piel

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

Related Questions