Search code examples
c++compiler-errorsheaderlinker

Function in source file already defined in another source file error


// file1.h
#pragma once
void public1();
// file1.cpp
#include "file1.h"
void privateFunc() {}
void public1() {}
// file2.h
#pragma once
void public2();
// file2.cpp
#include "file2.h"
void privateFunc() {}
void public2() {}
// main.cpp
#include <iostream>
#include "file1.h"
#include "file2.h"
int main()
{
    std::cout << "Hello World!\n";
}

So I have 2 functions in the 2 implementation files that have the same name and same parameters, but the implementation is different. Both are not included in their header file, so I assume they compiler can distinguish them. I think this is the problem.

How can I make function privateFunc() private to the implementation file without putting it in a class? That is, when another file includes "file1.h" or "file2.h", it should not know privateFunc() exists.


Solution

  • To make a function private, you must declare it as static. Otherwise that symbol will be made available to the linker for resolving across multiple sources.

    static void privateFunc() {}
    

    Alternatively, you can declare it in an unnamed namespace:

    namespace
    {
        void privateFunc() {}
    }
    

    You can read more about unnamed namespaces here.