Search code examples
c++dev-c++

Undefined reference to class member function when using more than 1 source file


I'm trying to learn how to seperate header and implementation files but it is not working even though i tried to keep it as simple as possible

header file

// foo.h
#ifndef FOO_H
#define FOO_H

struct Foo{
    void bar();
};

#endif

implementation file

 // foo.cpp
 #include "foo.h"
 #include <iostream>

 void Foo::bar(){
     std::cout << "test";
 }

main file

// test.cpp
#include <iostream>
#include "foo.h"

int main(){
    Foo foo;
    foo.bar();
}

when i try to compile this, it throws an error

test.cpp:(.text+0x15): undefined reference to `Foo::bar()'


Solution

  • In order to compile multiple files, you would add both .cpp files to your project under the same target. Then your DEV C++ IDE will automatically add both files to the build and link them together.

    On the completely, different note, Please avoid using DEV C++, it is very very old and hasn't seen updates in years. I'd recommend CodeBlocks instead.