Rüp*_*ure 4 c pragma include c-preprocessor preprocessor-directive
我#pragma在函数内部使用了指令而没有错误或警告(特别是#pragma pack()).但是下面的代码显示了警告incompatible implicit declaration of built-in function 'printf'|:
int main(void)
{
printf("Trial");
}
#include<stdio.h>
Run Code Online (Sandbox Code Playgroud)
此外,这是我所拥有的一本书的摘录.作者对SO的评价很差,特别是对他的慷慨使用void main(),但我觉得没有作者在没有理由的情况下声称以下内容是不是很糟糕:
这些预处理程序指令中的每一个都以#符号开头.指令可以放在程序的任何位置,但通常放在程序的开头,在第一个函数定义之前.
那么你能告诉我是否必须使用一些预处理器指令,比如#include在程序的顶部,而其他类似的指令#pragma可以在程序的任何地方使用?
编辑在OUAH的评论之后我尝试了以下内容,但它没有发出警告,它给出了一大堆错误 .LOL.
int main(void)
{
#include<stdio.h>
printf("Trial");
}
Run Code Online (Sandbox Code Playgroud)
的#include指令可以在任何地方在源文件中被放置,但在C可以已被声明之前它通常不被使用的标识符.这就是你将#include指令放在源文件开头的原因.
void foo(void)
{
printf("Hello world\n");
}
extern int printf(const char *, ...); // Error, the declaration should be put
// before the actual call
Run Code Online (Sandbox Code Playgroud)
这样想吧.包含文件的内容只是插入到#include指令出现的文件中.生成的代码需要在语法上对您编程的语言更正.
设置以下文件:
int a;
int foo();
int main()
#include "myheader.h"
int foo()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
文件myheader.h包含:
{
return foo();
}
Run Code Online (Sandbox Code Playgroud)
编译器在预处理器处理完#include指令后将看到的代码是:
int a;
int foo();
int main()
{
return foo();
}
int foo()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是有效的C语法.建议不要使用#include指令,但它可以让您了解它的含义.如果myheader.h文件具有以下内容:
this is some garbage
which is not proper C
Run Code Online (Sandbox Code Playgroud)
然后生成的代码将是:
int a;
int foo();
int main()
this is some garbage
which is not proper C
int foo()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以在文件中的任何位置使用#include.它导致在该点包含所包含文件的内容.您在代码中获得printf()的未声明消息的原因是C要求在使用之前声明函数,并且stdio.h具有该声明.这就是为什么它需要在它使用之前.为什么它不能包含在后一个例子中的main()中是因为在包含(扩展)时,它会导致语法错误的C代码.