Search code examples
c++compiler-errorsg++subdirectory

C++ Undefined Reference When Compiling .h and .cpp in Subfolders


Long story short I want to put my .h and .cpp files in subfolders (include and src respectively) and reference them in my main.cpp file but I am receiving an error of:

main.cpp:(.text+0x47): undefined reference to `Kmer::Kmer()'.

when compiling using:

g++ -I /path/to/MyFolder/include main.cpp.

My files are structured like below:

  • MyFolder
    • main.cpp
    • include
      • Kmer.h
    • src
      • Kmer.cpp
//main.cpp
#include <iostream>
#include "Kmer.h"
using namespace std;

int main() {
    Kmer k;
    return 0;
};
//Kmer.h
#pragma once

class Kmer{
  public:
    Kmer();
  protected:
  private:
};
//Kmer.cpp
#include "Kmer.h"
#include <iostream>
using namespace std;

Kmer::Kmer(){
  // code here
  cout << "Kmer created" << endl;
}

I appreciate the help!


Solution

  • You are not compiling Khmer.cpp. You need to add it to your g++ compile line

    g++ -o <YOUR APPLICATION NAME> -I /path/to/MyFolder/include main.cpp src/Khmer.cpp