@clarazhang
2016-12-07T08:37:57.000000Z
字数 945
阅读 1642
关于头文件定义方法的分析
C 预处理
本调研分析1~5由李子天于2015.11.29提供,后续由张昱补充。
1.gcc file1.c file2.c
- head.h:
short int a = 10;
- file1.c:
#include "head.h"
main(){}
- file2.c:
#include "head.h"
链接器报错:a重定义
2.gcc file1.c file2.c
- head.h:
#ifndef _HEAD_H
#define _HEAD_H
short int a = 10;
#endif
- file1.c:
#include "head.h"
main(){}
- file2.c:
#include "head.h"
链接器报错:a重定义
3.gcc file1.c
- head.h:
short int a = 10;
- file1.c
#include "head.h"
#include "head.h"
main(){}
编译器报错:a重定义
4.gcc file1.c
- head.h:
#ifndef _HEAD_H
#define _HEAD_H
short int a = 10;
#endif
- file1.c
#include "head.h"
#include "head.h"
main(){}
正常编译运行。
5.gcc file1.c file2.c file3.c
- head.h:
extern short int a;
- file1.c:
#include "head.h"
main(){}
- file2.c:
#include "head.h"
- file3.c:
short int a = 10;
正常编译运行。
6.gcc file1.c file3.c
- head.h:
short int a = 10;
- file1.c:
#include "head.h"
main(){}
- file3.c:
#ifndef _HEAD_H
#define _HEAD_H
#include "head.h"
#endif
链接器报错:a重定义
7.gcc file1.c file3.c
- head.h:
#ifndef _HEAD_H
#define _HEAD_H
short int a = 10;
#endif
- file1.c:
#include "head.h"
main(){}
- file3.c:
#ifndef _HEAD_H
#define _HEAD_H
#include "head.h"
#endif
正常编译运行。