Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

c++ - Multiple definition of a function error, even when using #if guard clauses

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.

File UTIL.h

#ifndef UTIL_H_
#define UTIL_H_

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

#endif /* UTIL_H_ */

File ClassA.h

#ifndef CLASSA_H_
#define CLASSA_H_

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

#endif /* CLASSA_H_ */

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
}

File ClassB.h

#ifndef CLASSB_H_
#define CLASSB_H_

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

#endif /* CLASSB_H_ */

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
}

Compile error message

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First variant - use inline specifier

#ifndef UTIL_H_
#define UTIL_H_

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

#endif /* UTIL_H_ */

Second variant - write definition in .cpp file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...