Potaito
Potaito

Reputation: 1190

hpp/cpp split with global function: Multiple definition of ... error

EDIT: The problem is the forgotten include guard. Sorry!

So I'm trying to consequently apply two file rule where all declarations go into a .hpp file and all definitions into the corresponding .cpp file. My problem are global functions in libraries whose header gets included in multiple locations.
For example:

/* lib1.hpp */
namespace lib1{
int addNumbers(int a, int b);
}

and the cpp file:

/* lib1.cpp */
namespace lib1{
int addNumbers(int a, int b) {return a + b;}
}

Now if I include lib1.hpp in multiple libraries, say lib2, lib3 and then include both, lib2 and lib3 in any other library or executable-file,

I get the multiple definitions of addNumbers() error.

This makes sense to me, but I can't figure out how to solve this issue. I tried the extern keyword, but it doesn't change anything:

/* lib1.hpp */
namespace lib1{
extern int addNumbers(int a, int b);
}

and the cpp file remains the same:

/* lib1.cpp */
#include "lib1.hpp"

namespace lib1{
int addNumbers(int a, int b) {return a + b;}
}

It would work if I created a surrounding class for the functions in lib1.hpp, but that doesn't help me understand the problem and adds a redundant namespace like lib1::lib1::addNumbers() for instance.

Upvotes: 1

Views: 2693

Answers (3)

Afshin
Afshin

Reputation: 392

As "Let Us Embed" has told use preprocessor directives to avoide repetitive declarations.

# pragma once ///if the compiler supports 

for other compilers use:

#ifndef EXAMPLE
#define EXAMPLE
Add your code
#endif

Upvotes: 1

knivil
knivil

Reputation: 807

1.) Add inline keyword if your function should be defined in a header file.

2.) I think names that start with two underscores are reserved for the compiler.

Upvotes: 1

Embedded C
Embedded C

Reputation: 1474

Try to use a #define in your .hpp file as shown below

/* lib1.hpp */
#ifndef __LIB_1__
#define __LIB_1__
namespace lib1{
int addNumbers(int a, int b);
}
#endif /*__LIB_1__*/

Upvotes: 0

Related Questions