#include 比它出现在程序中更早

#include is required sooner than it appears in the program

我有一个 header,其中一个函数声明是否定义了 DEBUG

我也有这个函数的定义,它的工作原理是一样的。但我会知道 DEBUG 是否仅在 main() 中定义,然后再检查参数。

我已将 #include 放入 main():

header:

#ifdef DEBUG
void printStack(Stack* st);
#endif

函数定义所在的文件

#ifdef DEBUG
void printStack(Stack* st)
{
    int i;
    for (i = 0; i < st->size; i++)
        printf(ValType_IOSPECIF " ",st->data[i]);
    printf("\n");
}
#endif

文件,其中 main() 是

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "calculating.h"

#define EXPR_LENGTH 1000

int main(int argc, char* argv[])
{
    int argflag = 0;
    if (argc >= 2)
        argflag = !strcmp(argv[1], "-debug");

#if (argflag)
#define DEBUG
    printf("! DEBUG !\n\n\n")
#endif

#include "stack.h" // there is a that function here
...
}

对吗?

But I will know if DEBUG is defined only into main() after arguments checking.

...

Is it right?

不,那是不对的。

DEBUG是一个预处理器宏,在编译每个源文件时,在编译时定义或不定义。有可能编译 main.c 时定义了 DEBUG 但在编译定义 printStack.

的源文件时没有定义

如果您使用 make 或 IDE,很可能 DEBUG 已定义或未定义,用于编译每个源文件,但语言中没有任何内容保证。

您混淆了 C 和预处理器宏:

在编译源代码之前,以 # 开头的所有内容都被预处理器替换,并且只有在运行时才会执行 main

所以,不,你做的不对。

您不能在运行时 #define#if;这是编译前的事情。只需使用 C 的普通变量和 if 控制机制。

你的错误强烈表明你没有通过连贯的教程或 C 书来学习这门语言。也许您想学习新文学;我能想到的任何 C 教程都会教您如何快速完成此操作。

不,那是错误的。您正在尝试根据传递的参数确定预处理的结果。这是您的代码的简化版本:

#define EXPR_LENGTH 1000

int main(int argc, char* argv[])
{
    int argflag = 0;
    if (argc >= 2)
        argflag = !strcmp(argv[1], "-debug");

#if (argflag)
#define DEBUG
    printf("! DEBUG !\n\n\n")
#endif
}

使用 clang -E main.c 预处理:

int main(int argc, char* argv[])
{
 int argflag = 0;
 if (argc >= 2)
  argflag = !strcmp(argv[1], "-debug");





}

Preprocess 在编译之前完成,也就是在执行之前,开始。所以不可能在运行时确定预处理的结果。