Gerrie
Gerrie

Reputation: 786

Macro definition not replaced as expected?

I followed the online tutorial and wanted to use #undef to design my debug output function. I wrote a debugOut.h file. The content is as follows:

#include <stdio.h>

#define NOOP //(void(0))

#undef DEBUG_PRINT

#if DEBUG_OUT
#define DEBUG_PRINT printf
#else 
#define DEBUG_PRINT(...) NOOP
#endif 

#undef DEBUG_OUT

Then I wrote a main function to test whether my design is correct.

#include<iostream>
#include "Header/debug_out.h"
#define DEBUG_OUT
int main(){
    DEBUG_PRINT("module1 debug...\n");
    printf("hello,world");
}

But the output result is only hello, world. Why I defined #define DEBUG_OUT, why is DEBUG_PRINT not replaced with printf

I wrote it based on an online tutorial. I want to write an output function for c++ based on this. But in the sentence #define DEBUG_PRINT(...) NOOP, what does (...) represent? Is there any way I can output what the macro definition is replaced with?

Upvotes: 3

Views: 446

Answers (2)

road
road

Reputation: 49

#include <stdio.h>

#define NOOP //(void(0))

#undef DEBUG_PRINT

#if DEBUG_OUT      ///////////should be #ifdef
#define DEBUG_PRINT printf
#else 
#define DEBUG_PRINT(...) NOOP
#endif 

#undef DEBUG_OUT

below is copied from the voted most.

#include<iostream>
#define DEBUG_OUT             // first define DEBUG_OUT 
#include "Header/debug_out.h" // when this is processed DEBUG_OUT is defined
int main(){
    DEBUG_PRINT("module1 debug...\n");
    printf("hello,world");
}

Upvotes: 2

Lukas-T
Lukas-T

Reputation: 11340

The preprocessor basically scans the input from top to bottom. So it first processes the #if DEBUG_OUT included from #include "Header/debug_out.h" and only then it processes #define DEBUG_OUT.

You need to make sure DEBUG_OUT is defined before the contents of Header/debug_out.h are processed. The following should work:

#include<iostream>
#define DEBUG_OUT             // first define DEBUG_OUT 
#include "Header/debug_out.h" // when this is processed DEBUG_OUT is defined
int main(){
    DEBUG_PRINT("module1 debug...\n");
    printf("hello,world");
}

In Addition there is a typo in "Header/debug_out.h":

#if DEBUG_OUT

should be

#ifdef DEBUG_OUT

Upvotes: 7

Related Questions