Search code examples
multithreadingc++11visual-c++lnk2005

Multi threaded function already defined in .obj


I've searched for the error LNK2005 "already defined in .obj" but can't find content related to the specific problem I am facing. Hope someone can help me on this...

I've a header foo.h

// foo.h

#ifndef FOO_H
#define FOO_H

void foo() {
    print("foo\n");
}

#endif

and main file... main.cpp

// main.cpp

#include <thread>
#include "foo.h"

int main() {

    std::thread t(foo);
    t.join();

    return 0;
}

Now, it compile without any errors and gives the gives output to the console...

foo

But if I create another file foo.cpp and just include the header foo.h and do nothing else...

// foo.cpp

#include "foo.h"

...I get linker error LNK2005 "void __cdecl foo(void)" (?foo@@YAXXZ) already defined in main.obj

Don't know what's going wrong here.?!!


Solution

  • You must place only the prototype of the foo() function in the header file, and the implementation once in the .cpp.

    Thus, foo.h must contain:

    #pragma once
    void foo();
    

    And foo.cpp:

    #include "foo.h"
    
    void foo() {
        printf("Whatever");
    }