C++ linking object's files (G++)

拟墨画扇 提交于 2019-12-11 08:49:55

问题


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;
}

This commands return:

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

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

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

main.o: In function `main': main.cpp:(.text+0x11): undefined reference to 'CIntegerType< unsigned int>::Show()' collect2: ld returned 1 exit status


回答1:


Try putting your template implementation in the header file.

See: Why can templates only be implemented in the header file?




回答2:


Try g++ -Wall -pedantic -o main.o class.o instead. You are facing the same problem as in this question: g++ linking order dependency when linking c code to c++ code

The linker searches for functions in the order they appear. Since you have a template function, its use in main must be fed to the linker prior to the actual code to instantiate it in class.



来源:https://stackoverflow.com/questions/16800983/c-linking-objects-files-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!