标签:style blog http io ar color os 使用 sp
很多人上了这么多年学,学了这么多年课,考了这么多年试,写了这么多年程序,到头来,问问你#include是什么意思,却只能简单的说说那是一个预处理命令。然后在深问一下,什么是预处理命令,然后就卡壳了。下面我们就来一起瞎折腾一下,看看#include背后的故事。
一般来说,我们都是#include <stdio.h>的,但是今天我不这样写。
先看看我的工程,我的Project中有三个文件,main.cpp ,Foo.txt, Foo.c。这里要看清楚了,我没有使用Foo.h,而是使用了Foo.txt。好了,废话不说了,先来看看Foo.txt里面的内容。
/*
*FileName: Foo.txt,NOT Foo.h
*/
#ifndef foo_txt_
#define foo_txt_
#ifdef __cplusplus
extern "C"{
#endif
#define NUMBER (1+1*1)
int Foo(void);
#ifdef __cplusplus
}
#endif
#endif //all the file
下面看Foo.c,这个源文件只是简单的实现了Foo。下面是代码:
#include "Foo.txt"
int Foo(void)
{
return NUMBER;
}#include <iostream>
#include "Foo.txt"
using namespace std;
int main()
{
cout<<Foo()<<endl;
return 0;
}g++ -Wall main.cpp foo.c -o main.exe
其实#include只是简单的复制了头文件中的内容一次到源文件中。我们可以使用cpp命令来看看经过处理后的Foo.c。使用gcc输入:
cpp foo.c >foo.i
# 1 "Foo.c"
# 1 "<command-line>"
# 1 "Foo.c"
# 1 "Foo.txt" 1
# 13 "Foo.txt"
int Foo(void);
# 2 "Foo.c" 2
int Foo(void)
{
return (1+1*1);
}
好了,今天的解释就到这了,希望看完之后能够明白几个问题:
1.有关某些渣渣教科书喜欢#include "XXX.c",这样编译器却不会报错,但是不是一种好的方法。
2.问什么要在头文件的前面加上#ifndef。
3.为什么不能再头文件中给声明变量并赋值,例如:int number=10;
标签:style blog http io ar color os 使用 sp
原文地址:http://blog.csdn.net/u011589289/article/details/41389829