Domanda

Possible Duplicate:
C++ templates, undefined reference

I have a very simple program consisting of three files, which builds vectors from plain arrays:

//create.hpp

#ifndef CREATE_HPP_
#define CREATE_HPP_

#include <vector>

using namespace std;

template<class T>
vector<T> create_list(T uarray[], size_t size);

#endif /* CREATE_HPP_ */

//create.cpp

#include "create.hpp"

template<class T>
vector<T> create_list(T uarray[], size_t size){
    vector<T> ulist(uarray, uarray + size);
    return ulist;
}

//main.cpp

#include <vector>
#include <iostream>

#include "create.hpp"

using namespace std;


int main(){
    char temp[] = { '/', '>' };
    vector<char> uvec = create_list<char>(temp, 2);

    vector<char>::iterator iter=uvec.begin();
    for(;iter != uvec.end();iter++){
        cout<<*iter<<endl;
    }

    return 0;
}

The build process is as follows:

g++ -O0 -g3 -Wall -c -fmessage-length=0 -o create.o create.cpp
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o main.cpp
g++ -o main.exe main.o create.o

While building the program, I get this error:

main.o: In function `main':
../main.cpp:18: undefined reference to `std::vector<char, std::allocator<char> > create_list<char>(char*, unsigned int)'

This program is really simple. However, the compilations passed successfully, but the link failed. Then I move all the code into a single file, and everything works like a charm. Can anybody help me figure this out?

È stato utile?

Soluzione

Yes. The answer is complicated. It has to do with how templates actually work in C++.

Short answer: the full template definition must be in the header file, or you must have an explicit instantiation (e.g. http://msdn.microsoft.com/en-us/library/by56e477(v=vs.80).aspx) for a given type in the CPP file.

Long answer (reason): templates are not code that can be compiled into a binary (object). They are merely a "recipe for creating code" and code can be created only at the process of instantiation. This is also why inaccurate usage of templates may result in long compilation times and larger than needed binaries.

Altri suggerimenti

You have defined your template in a separate .cpp file. Each file is compiled separately. Your create.cpp doesn't contain any running code so it is being discarded by the compiler. Later, at a linkage stage, when the linker tries to link the binary of main.cpp with create_list, it can't find it in other compiled objects thus you are getting this error. To resolve it you need to instantiate your template at least once in your create.cpp or have the implementation inside the header file.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top