文件:A.h .h中包含了函数实现
#ifndef _A_H
#define _A_H
#include "stdio.h"
void helloxxx()
{
printf("hello world\n");
}
#endif
库1:
T1.h
#ifndef _T1_H
#define _T1_H
#include "A.h"
class T1
{
public:
T1();
~T1();
};
#endif
T1.cpp
#include "T1.h"
T1::T1()
{
helloxxx();
}
T1::~T1()
{
}
库2:
T2.h
#ifndef _T2_H
#define _T2_H
#include "A.h"
class T2
{
public:
T2();
~T2();
};
#endif
T2.cpp
#include "T2.h"
T2::T2()
{
helloxxx();
}
T2::~T2()
{
}
可执行程序:test.cpp
#include "stdio.h"
#include "T1.h"
#include "T2.h"
int main()
{
T1 t;
T2 t1;
return 0;
}
然后,我们g++ -c T1.cpp,g++ -c T2.cpp,ar rcv libT1.a T1.o,ar rcv libT2.a T2.o,g++ -o test test.cpp -L./ -lT1 -lT2
出现重定义的原因很明显,由于包含的.h文件预处理的时候是直接在被包含的文件中展开的,所以我们每个.o文件(T1.o T2.o test.o)中都会有helloxxx的实现(也就是定义),所以在最后链接时出现了函数重定义错误
二、解决方法
方法1:不要在头文件中定义函数,而将声明和实现分别写在.h和.cpp中
方法2:.h中实现的函数加上static
#ifndef _A_H
#define _A_H
#include "stdio.h"
static void helloxxx()
{
printf("hello world\n");
}
#endif
改为这样,就ok了