"Undefined symbols for architecture x86_64"尝试包含另一个文件中的功能

"Undefined symbols for architecture x86_64" trying to include function from another file

本文关键字:另一个 包含 文件 功能 symbols Undefined for architecture x86      更新时间:2023-10-16

我试图在另一个程序event_rate.cpp中包含一个名为kinematic_factor的函数,该函数用kinematic_filter.cpp编写。

kinematic_factor.cpp:

#include "kinematic_factor.hpp"
double kinematicfactor (double md) {
    double mt = 17.6924; // Mass of Fluorine [GeV/c^2]
    double r = 4*mt*md/pow(mt+md, 2);
    return r;
}

kinematic_factor.hp:

#ifndef kinematic_factor_hpp
#define kinematic_factor_hpp
double kinematicfactor (double md);
#endif /* kinematic_factor_hpp */

事件速率:

#include "event_rate.hpp"
#include "kinematic_factor.hpp"
#include <iostream>
#include <cmath>
using namespace std;
int main() {
    cout << kinematic_factor(1.0) << endl;
}

据我所知,这是我应该做的,但我得到了一个错误:

Undefined symbols for architecture x86_64:
  "kinematicfactor(double)", referenced from:
      _main in event_rate-1d17f7.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我做错了什么?

编辑:我试过

#include "kinematic_factor.cpp"

它奏效了。但我听说包括cpp文件(而不是头文件)对学习者来说是一种糟糕的做法。。。我能做什么?

你们是如何编译这个程序的,我能够正确地编译同一个程序。我怀疑这应该是一个关联问题。

您需要将源代码一起编译才能进行编译和链接。

g++ kinematic_factor.cpp event_rate.cpp -o event_rate