使用 else 宏时出现 C 错误 "expected parameter declarator"

C error with using else macro "expected parameter declarator"

我写了下面的 C 代码(根据 C99 标准)并且 运行 没问题:

#include <stdio.h>

#ifdef _WIN32
printf("Running on Windows");
#endif

void test(int x);

int main() {
    return 0;
}

但是添加 else 导致了很多错误(大约 12 个)新代码有什么问题:

#ifdef _WIN32
printf("Running on Windows");
#else
printf("Running on Windows");
#endif

部分错误:

error: expected parameter declarator
expected ')'
warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
error: conflicting types for 'printf'

当您使用条件编译时,预处理器会在编译步骤之前将代码添加到您的程序中。 所以,如果符号 _WIN32 存在,那么你实际上是在说

printf("Running on Windows");

void test(int x);

int main() {
    return 0;
}

这在语法上是不正确的,因为您在所有函数之外都有可执行代码(对 printf 的调用)。

如果您在添加“#else”之前没有遇到问题,那是因为符号 _WIN32 不存在并且预处理器没有将 printf 语句添加到您的代码中。