最近在看mingw32中的头文件实现,发现函数在头文件中定义,多文件编译不会冲突。
发现其函数实现皆有修饰符static,实现只在单文件可见,防止多文件包含相同头文件函数定义冲突。
另外,类定义中的函数实现不会出现定义冲突的现象,即使两个相同的类名,相同的函数名。
错误情况:包含3个文件, my.h t1.cpp t2.cpp
//my.h
#ifndef __MY_H__
#define __MY_H__
int __max( int a, int b) {
return a-b;
}
#endif
//t1.cpp
#include "my.h"
main(){ }
//t2.cpp
#include "my.h"
使用 g++ t1.cpp t2.cpp -o a.exe
会报错,提示定义冲突
将 my.h 做如下更改:
//my.h
#ifndef __MY_H__
#define __MY_H__
static int __max( int a, int b) {
return a-b;
}
#endif
编译正常通过