我在函数中使用了#pragma
指令,没有错误或警告(尤其是#pragma pack()
)。但是下面的代码显示了警告incompatible内置函数 'printf'|
的隐式声明:
int main(void)
{
printf("Trial");
}
#include<stdio.h>
此外,这是我有一本书的摘录。作者对 SO 的评论很差,尤其是他对 void main()
的慷慨使用,但我仍然觉得没有作者可以 < strong>that 无故声称以下内容是不好的:
Each of these preprocessor directives begin with a # symbol. The directives can be placed anywhere in a program but are most often placed at the beginning of a program, before the first function definition.
那么你能告诉我是否必须在程序的顶部使用一些预处理器指令,如 #include
而其他的如 #pragma
可以在程序的任何地方使用程序?
编辑 在 OUAH 的评论之后我尝试了以下,但它没有给出警告,它给出了一大堆错误 .哈哈。
int main(void)
{
#include<stdio.h>
printf("Trial");
}
最佳答案
这样想。包含文件的内容简单地插入文件中#include 指令出现的位置。生成的代码需要在语法上符合您所使用的编程语言。
考虑以下文件:
int a;
int foo();
int main()
#include "myheader.h"
int foo()
{
return 0;
}
文件 myheader.h 包含:
{
return foo();
}
在预处理器处理完#include 指令后,编译器将看到的代码是:
int a;
int foo();
int main()
{
return foo();
}
int foo()
{
return 0;
}
这是有效的 C 语法。不建议这样使用 #include 指令,但它可以让您了解它的含义。如果 myheader.h 文件具有以下内容:
this is some garbage
which is not proper C
那么生成的代码将是:
int a;
int foo();
int main()
this is some garbage
which is not proper C
int foo()
{
return 0;
}
您可以在文件中的任何位置使用#include。它会导致此时包含文件内容的字面包含。您在代码中收到 printf() 未声明消息的原因是 C 需要在使用前声明函数,而 stdio.h 具有该声明。这就是为什么它需要在使用之前。为什么它不能包含在后一个示例中的 main() 中是因为在包含(扩展)时,它会导致语法上不正确的 C 代码。
关于像#include 这样的预处理器指令可以只放在程序代码的顶部吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389126/