头文件中全局函数多次引用出现重定义的问题记录

文件: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了

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值