函数错误的多重定义,即使使用#if保护子句也是如此 [英] Multiple definition of a function error, even when using #if guard clauses

查看:125
本文介绍了函数错误的多重定义,即使使用#if保护子句也是如此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的C ++项目创建一个简单的UTIL.h文件,其中包含aplusb(int,int)函数。但是我无法编译,并且错误消息是有关 aplusb(int,int)的多个定义的。

I am creating a simple UTIL.h file contain aplusb(int, int) function for my C++ project. However I cannot compile and the error message is about multiple definition of `aplusb(int, int)'. Would you please help me correct the error or give me some hints?

我在这里附上我的项目,以供您详细参考。

I attach here my project for your detail reference.

文件UTIL.h

#ifndef UTIL_H_
#define UTIL_H_

int aplusb(int a, int b) {
    return a + b;
}

#endif /* UTIL_H_ */

文件ClassA.h

File ClassA.h

#ifndef CLASSA_H_
#define CLASSA_H_

class ClassA {
public:
    ClassA();
    virtual ~ClassA();
private:
    int sum;
};

#endif /* CLASSA_H_ */

文件ClassA.cpp

File ClassA.cpp

#include "ClassA.h"
#include "UTIL.h"

ClassA::ClassA() {
    // TODO Auto-generated constructor stub
    sum = aplusb(3,5);

}

ClassA::~ClassA() {
    // TODO Auto-generated destructor stub
}

文件ClassB.h

File ClassB.h

#ifndef CLASSB_H_
#define CLASSB_H_

class ClassB {
public:
    ClassB();
    virtual ~ClassB();
private:
    int sum;
};

#endif /* CLASSB_H_ */

文件ClassB.cpp

File ClassB.cpp

#include "ClassB.h"
#include "UTIL.h"

ClassB::ClassB() {
    // TODO Auto-generated constructor stub
    sum = aplusb(5,6);
}

ClassB::~ClassB() {
    // TODO Auto-generated destructor stub
}

编译错误消息

ClassB.o: In function `aplusb(int, int)':
/home/vtvan/Desktop/workspace/commonfunc/UTIL.h:11: multiple definition of `aplusb(int, int)'
ClassA.o:/home/vtvan/Desktop/workspace/commonfunc/UTIL.h:11: first defined here
collect2: error: ld returned 1 exit status
make: *** [commonfunc] Error 1


推荐答案

第一个变体-使用 inline 说明符

First variant - use inline specifier

#ifndef UTIL_H_
#define UTIL_H_

inline int aplusb(int a, int b) {
    return a + b;
}

#endif /* UTIL_H_ */

第二变体-在 .cpp 文件中写入定义。

Second variant - write definition in .cpp file.

这篇关于函数错误的多重定义,即使使用#if保护子句也是如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆