Hi,

Assume that we want to define a set of template function separately & then use them in other files, by calling their header.

1. Shoud we put function body (both define & declare) in header file as well. My current code works this way. But when I put those body in the *.cpp file then it is compiled & linked without error. But crashes run time!
2. I need to use some of those function in other file as well. But if I put function body in *.h files then I recieve mutliple definition error when linking (I already have one #ifnedef block covering all mu header code)

Any suggestion/Alternative?

Thanks in advance,
Reza

hey
according to me the program crashing should be a different reason as i have included a cpp file in programs and run them without error.. post the problematic code..

Hello,
Let's not refer to ourselve but to compiler!
Try this:
__________________________
File 1: Main.cpp
__________________________

#include <stdio.h>
#include "ADD2.h"

int main (int argc, char * const argv[]) {
    int a=3;
    float b=3.3;
printf("na=%d t ADD2(a)=%d",a,ADD2(a));
printf("nb=%f t ADD2(b)=%f",b,ADD2(b));   
}

__________________________
File 2: ADD2.h
__________________________

#ifndef ADD2_H
#define ADD2_H 
template <class T>
T  ADD2(T a);

template <class T>
T ADD2(T a)
{
 a=a+(T)2;
}
#endif

__________________________
This just works fine but if you remove function body then like this:
Modified File 2: ADD2.h
__________________________

#ifndef ADD2_H
#define ADD2_H 
template <class T>
T  ADD2(T a);
#endif

__________________________
ADDED File 3: ADD2.cpp
__________________________

#include  "ADD2.H"
template <class T>
T ADD2(T a)
{
 a=a+(T)2;
}

__________________________
This Time again it will be compiled but a run time error like this can happen:
ZeroLink: unknown symbol '__Z4ADD2IiET_S0_'

It seems clear that we must define all the template in *.hpp??

What's your compile command line?

I use gcc 3.3++ on MAC or Xcode. But from concept of template it could be clear that it must be implemented in *.h, so on linking time required instances can be made?

Am I right?
:rolleyes:

Put the implementation in an .hpp file and have it include the .h.

Then, in your main program file, include the .hpp file rather than the .h
Also, I think you want a reference in your ADD2 function (T & a), otherwise, I don't think 'a' will change... Also, you don't return anything in your function, you're supposed to return a T.

Thanks,

This was just a test file.

BTW, putting the implementation in an *.hpp file is still in header file. I am not receiving my answer, how refering from an *.hpp file to *.h file can help me?

Thanks,Reza

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.