c语言一个最最基础的问题——include的用法。

为了搞清楚include的用法,我做了个小实验,三个文件如下。

(1)myprint.c
#include <stdio.h>
#include "myprint.h"

void myprint()
{
printf("This is myprint!\n");
}

(2)myprint.h
#ifndef _MY_PRINT_H_
#define _MY_PRINT_H_

void myprint();

#endif

(3)main.c
#include <stdio.h>

#include "myprint.h"

void myprint()
{
printf("This is myprint!\n");
}

用gcc编译如下:

gcc -c myprint.c -o myprint.o
gcc -c main.c -o main.o
gcc main.o myprint.o -o main

执行:
./main
This is myprint!

都没问题。

之后我在main.c中,将#include "myprint.h"这一行注释掉,变为
(3)main.c
#include <stdio.h>

//#include "myprint.h"

void myprint()
{
printf("This is myprint!\n");
}

同样按照以上的编译执行,竟然还可以通过,没有任何错误,这点很奇怪。
以上我的实验问题再哪,为什么注释掉#include "myprint.h"之后还可以编译通过?

1、C语言预处理器指令#include用于在编译期间把制定文件的内容包含进当前文件中,又称文件包含指令。
在源文件中,任何形如
#include "文件名"

#include <文件名>
的行都被替换为由文件名指定的文件的内容。如果文件名用引号引起来,则在源文件所在位置查找该文件;如果在该位置没有找到文件,或者如果文件名是用<>括起来的,则将根据相应的规则查找该文件,这个规则同具体的实现有关。
2、被包含的文件本身也可以包含#include指令。如果某个被包含文件的内容发生了变化,那么所有依赖于该包含文件的源文件都必须重新编译。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-01-28
#include<stdio.h>
void
main()
{
int
n=1,s=0;
while(n<=100)
{
s+=n;
n++;
if(n%2==1)//
等号是两个
continue;
}
printf("1到100的所有偶数和为%d\n",s);
}
希望能帮到你,不懂的地方追问
第2个回答  2013-05-16
main.c
#include <stdio.h>

//#include "myprint.h"

void myprint()
{
printf("This is myprint!\n");
}

里面有了myprint()函数了,当然可以编译过了。
你试试改成:
main.c
#include <stdio.h>

//#include "myprint.h"

myprint()//这样应该会出错的!
/*void myprint()
{
printf("This is myprint!\n");
}*/追问

main()函数我贴错了,正确的应该是

main.c

#include

//#include "myprint.h"

int main()
{
myprint();
return 0;
}

问题是,注释掉#include "myprint.h"之后,还可以编译通过,没有任何错误。问题在哪?

追答

gcc main.o myprint.o -o main
myprint.o里有myprint()函数的,所以你不包括头文件myprint.h,也不会报错

本回答被网友采纳
第3个回答  2013-05-16
首先你要弄清楚#include<>和#include" "的区别就可以了,第一个是自动把系统的头文件链接进去,第二个是把你自己写的头文件连接进去.
第4个回答  2013-05-16
你贴出的main.c是正确的么?
我怎么没有看到main函数。
看了下你的myprint.h文件,,里面只是一个函数声明,并没有实现方法,函数的时候是在myprint.c里,你注释掉了include以后,C编译器在找不到声明的情况下,先会假设函数返回int,最后在你连接的时候连接了编译过的myprint.o,连接器就会找到里面的myprint函数,所以能编译成功。
所以你注释掉这个include,编译器一般发出警告信息,但不影响最终的编译结果

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网