【问题标题】:Not able to use printf in preprocessor directives [duplicate]无法在预处理器指令中使用 printf [重复]
【发布时间】:2020-03-21 16:27:10
【问题描述】:

我在执行下面的代码时遇到错误。谁能解释我在做什么错误?

#include <iostream>
using namespace std;
#define one 1
#ifdef one
    printf("one id defined");
#endif
void func1(); 
void __attribute__((constructor)) func1(); 
void func1() 
{ 
        printf("before"); 
} 
int main() 
{ 
    cout <<"main";
    return 0; 
} 

以下是我遇到的错误。

prog.cpp:5:11: error: expected constructor, destructor, or type conversion before '(' token
     printf("one id defined");
           ^

【问题讨论】:

  • 您不能在任何函数之外执行代码。唯一的例外是对象的初始化。
  • 您只能从main() 中调用一个函数,另一个函数或方法。您对printf 的调用不在此范围内。
  • 在编译期间打印消息:stackoverflow.com/questions/3826832/…
  • 如果您解释一下您期望这样做会有所帮助。您预计什么时候会出现输出?
  • 另外,这感觉就像您将宏用于它们不打算用于的东西。如果您确实使用了宏,请始终为它们提供完整的大写名称(如 ONE),以避免在几个月后阅读代码时出现混淆!

标签: c++ preprocessor


【解决方案1】:

不清楚这段代码应该实现什么,看看扩展代码看看有什么问题(-E for gcc)。这将类似于:

#include <iostream>
using namespace std;


printf("one id defined");

void func1(); 
void __attribute__((constructor)) func1(); 
void func1() 
{ 
        printf("before"); 
} 
int main() 
{ 
    cout <<"main";
    return 0; 
} 

但是你不能在文件范围内调用函数。可能存在声明/定义,这就是编译器需要构造函数、析构函数或类型转换的原因。

PS:你包含&lt;iostream&gt;,然后使用printf。这有点奇怪。 printf&lt;cstdio&gt;

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2012-06-29
    • 2015-09-29
    • 2018-01-29
    • 1970-01-01
    相关资源
    最近更新 更多