Search code examples
c++functionincludeclangundefined-symbol

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


I am trying to include a function called kinematicfactor, written in kinematic_factor.cpp in another program event_rate.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.hpp:

#ifndef kinematic_factor_hpp
#define kinematic_factor_hpp

double kinematicfactor (double md);

#endif /* kinematic_factor_hpp */

event_rate:

#include "event_rate.hpp"
#include "kinematic_factor.hpp"

#include <iostream>
#include <cmath>

using namespace std;

int main() {
    cout << kinematic_factor(1.0) << endl;
}

As far as I could check, this was how I was supposed to do it, but I get an error:

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)

What am I doing wrong?

EDIT: I tried

#include "kinematic_factor.cpp"

And it worked. But I heard that including cpp files (and not header files) is a bad practice for learners... What can I do?


Solution

  • How did you compile this program, I am able to compile same program correctly. I suspect it should be linking issue.

    You need to compile source together to compile and link.

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