预处理器指令定义和ifdef不能像我想象的那样工作?

use*_*967 3 c c-preprocessor

我有3个文件:

main.c中

#include <stdio.h>
#include <stdlib.h>
#include "test.h"

#define DEBUG

int main()
{
  testFunction();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

test.h

#ifndef TEST_H
#define TEST_H
#include <stdio.h>
#include <stdlib.h>

void testFunction();

#endif // TEST_H_INCLUDED
Run Code Online (Sandbox Code Playgroud)

test.c的

#include "test.h"

void testFunction(){
  #ifdef DEBUG
    printf("I'm inside the testFunction\n");
  #endif
}
Run Code Online (Sandbox Code Playgroud)

问题:为什么程序不能在#ifdef DEBUG块中打印东西?如果我在test.h或test.c中写#define DEBUG一切都很好.那么在main.c中#define DEBUG的问题是什么?谢谢.

小智 11

预处理器指令定义和ifdef不能像我想象的那样工作?

不,不完全.您似乎相信预处理程序指令遍历文件边界,而它们不会.d预处理器宏的范围#define只是它定义的单个文件,或者仅当其他#include文件包含宏定义的文件时才是其他文件.

也许有必要想象你在每个文件上单独运行编译器(以及预处理器)(即使你没有意识到,也会这样做).预处理器无法告诉DEBUG已经在文件中定义它不能操作的文件.