Reputation: 1291
I have a utility file with a template function and an 'ordinary' function:
#ifndef __UTILS_CPP__
#define __UTILS_CPP__
#include <stdlib.h>
template<typename T> int makeIntN(const T V) { return (int)V;}
int makeIntS(const char *pVal) { return atoi(pVal);}
#endif
These functions are used by two other classes, subA and subB.
SubA.h:
#ifndef __SUBA_H__
#define __SUBA_H__
class SubA {
public:
SubA() {};
static int actionN(int i);
int actionS(const char *p);
};
#endif
SubA.cpp:
#include "suba.h"
#include "utils.cpp"
int SubA::actionN(int i) {
return makeIntN(i);
}
int SubA::actionS(const char *p) {
return makeIntS(p);
}
SubC.h
#ifndef __SUBC_H__
#define __SUBC_H__
class SubC {
public:
SubC() {};
int actionN(float f);
static int actionS(const char *p);
};
#endif
SubC.cpp
#include "subc.h"
#include "utils.cpp"
int SubC::actionS(const char *p) {
return makeIntS(p);
}
int SubC::actionN(float f) {
return makeIntN(f);
}
In main(), i create instances of these classes and call some of their methods:
cltest.cpp:
#include <stdio.h>
#include "suba.h"
#include "subc.h"
int main() {
int iResult = -1;
SubA *psa = new SubA();
iResult = psa->actionN(17);
printf("Res A: %d\n", iResult);
iResult = psa->actionS("17");
printf("Res A: %d\n", iResult);
SubC *psc = new SubC();
iResult = psc->actionN(17.65);
printf("Res C: %d\n", iResult);
return iResult;
}
When i compile this like this:g++ clstest.cpp subc.cpp suba.cpp
, i obviously get an error because makeIntS() is included each by SubA and SubC.
I tried various ways of #include
s and different ways to link, but either makeIntN()
is undefined or else makeIntS()
is muitply defined.
How can i get this to compile & link without splitting up the utils file into a template part and a non-template part?
Upvotes: 1
Views: 208
Reputation: 12283
There are 3 ways of having a non-template free function defined in a header file:
inline
static
I suggest you to go for making a int makeIntS(const char *pVal);
function inline
.
Upvotes: 2