c++ - c++ : linker command failed 中头文件的问题

标签 c++ c++11 header-files

提前道歉我确定这是一个非常简单的问题,但我一直无法找到解决方案。我正在将一个非常简单的 C++ 项目放在一起,但在正确使用头文件时遇到了问题。

目录结构如下:

.
├── mainGraph
│   └── hnsw.cpp
└── utils
    ├── distances.cpp
    └── distances.h

距离头文件(distances.h):

#ifndef DISTANCES
#define DISTANCES

#include <vector>

enum class Metric { Cosine, Euclidean};

double distance(const std::vector<double>& A, const std::vector<double>& B, Metric metric);
double similarity(const std::vector<double>& A, const std::vector<double>& B, Metric metric);

#endif

最后hnsw.cpp:

#include "../utils/distances.h"
#include <vector>
#include <iostream>

int main(){
    std::vector<double> A = {0.1, 0.5, 0.7, 1.1};
    std::vector<double> B = {0.5, 0.3, 0.8, 0.9};

    std::cout << distance(A, B, Metric::Cosine) << '\n';
}

现在,当我实际尝试使用以下命令编译 hnsw.cpp 时:g++ hnsw.cpp --std=c++11 我收到以下错误:

Undefined symbols for architecture x86_64:
  "distance(std::__1::vector<double, std::__1::allocator<double> > const&, std::__1::vector<double, std::__1::allocator<double> > const&, Metric)", referenced from:
      _main in hnsw-ad0e05.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

如果我将 main 移动到 distances.cpp 文件中,那么一切都会顺利进行。为了简洁起见,我没有发布整个文件,因为它很大,而且我很确定它不相关。如果这里有任何关于了解一般过程的资源,那也会非常有帮助。

最佳答案

如果您不想为以后的链接构建单独的目标文件,而是一次构建整个可执行文件,您需要在命令行上指定所有参与的翻译单元:

g++ -std=c++11 hnsw.cpp ../utils/distances.cpp

输出文件将被称为 a.out,除非您还使用 -o 标志覆盖该名称。

通常您会单独编译翻译单元并在单独的步骤中链接它们:

g++ -std=c++11 mainGraph/hnsw.cpp -c -o mainGraph/hnsw.o
g++ -std=c++11 utils/distances.cpp -c -o utils/distances.o

g++ -std=c++11 mainGraph.hnsw.o utils/distances.o -o myprog

您也不会手动维护这些命令,而是将它们粘贴到 Makefile 或某些等效的构建系统中。关键是您不需要重新编译没有改变的翻译单元,只是因为您更改了源代码的某些部分。

关于c++ - c++ : linker command failed 中头文件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43081164/

相关文章:

c++ - "A"之前的预期构造函数、析构函数或类型转换

c++ - 函数模板参数推导模板参数vs默认模板参数vs返回类型

c++ - 如何正确地从函数返回中 move 对象?

c++ - gcc 中非 MoveConstructible 函数对象的 std::function

c++ - 给定源文件的 header "corresponding"是否有技术名称?

cocoa - NSCocoaErrorDomain 错误代码常量在哪里定义?

c++ - c++中 vector 和列表的setter和getter

c++ - 缺少 boost::property_tree::ordered_end()

c++ - 使用元组累加器减少推力

c++ - 为什么我不应该包含 cpp 文件而使用 header ?