c++ - 为什么是 undefined reference ?

标签 c++ undefined-reference

在我的 test.cpp 中我有:

#include <iostream>
#include "first.h"
using namespace std;

int main ()
{
    auto dliste = d::data_preparation::prepare_d(100);
    cout << "Hello World!\n";
    return 0;
}

在我的 first.h 中我有:

namespace d {
    namespace data_preparation {
        something;
        std::vector<row<mdata::dliste>> prepare_d(int f);
        something;
    }
}

在我的 first.cpp 中我有:

#include "first.h"
something;
namespace d {
    namespace data_preparation {
        vector<row<mdata::dliste>> prepare_d(int f) {
            vector<row<mdata::dliste>> dliste;
            cout << f << '\n';
            return dliste;
        }
    }
}

当我编译这个时,我得到:

undefined reference to `d::data_preparation::prepare_d(int)'

已编辑

在我的 Makefile 中我有:

test: test.o
        $(CXX) -o $@ $(LDFLAGS) $^ $(LDLIBS)

我应该以某种方式修改它吗?

最佳答案

您很可能忘记将 first.cpp 链接到您的可执行文件。

只需运行以下命令(如果您使用的是 gcc):

g++ -c first.cpp -o first.o
g++ -c test.cpp -o test.o
g++ test.o first.o

或者只使用精简版:

g++ first.cpp test.cpp -o app

您应该按照以下行编辑您的 Makefile:

app: test.o first.o
    $(CXX) $^ -o $@ $(LDFLAGS) $(LDLIBS)

test.o: test.cpp
    $(CXX) -c test.cpp -o first.o

first.o: first.cpp
    $(CXX) -c first.cpp -o first.o

注意:我不得不使用 4 个空格进行缩进,但 Makefile 可能需要制表符。

关于c++ - 为什么是 undefined reference ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15518859/

相关文章:

c++ - CMake - 尝试构建项目时遇到 undefined reference

c - undefined reference 添加到现有文件和标题

c++ - 带有 For 循环和指针操作的 OPENMP

c++ - 调试 COM 引用计数器

c++ - 友元和嵌套类

c++ - 为什么此线程池死锁或运行太多次?

c++ - 类构造函数中冒号后的参数?

c - 对 `sin' 的 undefined reference ,即使我使用 <math.h> 和 -lm

c++ - 什么是 undefined reference /未解析的外部符号错误以及如何修复它?

c - 未定义的 Windows 引用 _ftprintf