C ++链接对象的文件(G ++)

时间:2013-05-28 20:33:16

标签: c++ g++ static-linking

class.h

#include <iostream>
#include <stdint.h>

using namespace std;

template <typename T>
class CIntegerType {
 public:
    void Show ( void );

 private:
    T m_Data;
};

class.cpp

#include "class.h"

template <typename T>
void CIntegerType<T> :: Show ( void ) {
    cout << m_Data << endl;
}

的main.cpp

#include "class.h"

int main ( void ) {
    CIntegerType<uint32_t> UINT32;

    UINT32 . Show ();

    return 0;
}

此命令返回:

g ++ -Wall -pedantic -c main.cpp

g ++ -Wall -pedantic -c class.cpp

g ++ -Wall -pedantic -o class.o main.o

main.o:在函数`main'中: main.cpp :(。text + 0x11):未定义引用'CIntegerType&lt; unsigned int&gt; :: Show()' collect2:ld返回1退出状态

2 个答案:

答案 0 :(得分:1)

请尝试使用g++ -Wall -pedantic -o main.o class.o。您遇到的问题与此问题相同:g++ linking order dependency when linking c code to c++ code

链接器按照它们出现的顺序搜索函数。由于您具有模板函数,因此必须在实际代码之前将其在main中的使用提供给链接器,以在class中实例化它。

答案 1 :(得分:1)

尝试将模板实现放在头文件中。

请参阅:Why can templates only be implemented in the header file?

相关问题