【问题标题】:C++ linking object's files (G++)C++ 链接对象的文件 (G++)
【发布时间】:2013-05-28 20:33:16
【问题描述】:

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

ma​​in.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::Show()' 的引用 collect2: ld 返回 1 个退出状态

【问题讨论】:

  • g++ -Wall -pedantic -o class.o main.o -- 看起来你缺少一个参数
  • 你可能需要切换对象,我记错了,但我认为你必须在编译时首先指定你的主循环对象。
  • 试试把模板函数放在表头。见:stackoverflow.com/questions/495021/…

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    改用g++ -Wall -pedantic -o main.o class.o。您面临与此问题相同的问题:g++ linking order dependency when linking c code to c++ code

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

    【讨论】:

    • 谢谢。我尝试过这个。输出:/usr/bin/ld: /usr/lib/debug/usr/lib/i386-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 12 ...:在函数_start': (.text+0x18): undefined reference to main' collect2: ld 返回 1 个退出状态
    • 我尝试了两种变体“g++ -Wall -pedantic -o main.o class.o”和“g++ -Wall -pedantic -o class.o main.o”,但没有结果。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多