"multiple definition of function" linker error

I have 2 cpp files that declare and define a function with the same name. When I try to compile I get the following linker error:

1
2
func2.cpp:(.text+0x0): multiple definition of `Func()'
func1.cpp:(.text+0x0): first defined here 


Files:
func1.h (empty file)
 


func1.cpp
1
2
3
4
5
6
#include "func1.h"

void Func()
{
   
}


func2.h (empty file)
 


func2.cpp
1
2
3
4
5
6
#include "func2.h"

void Func()
{
   
}


main.cpp
1
2
3
4
5
6
7
8
9
10
#include <iostream>

#include "func1.h"
#include "func2.h"

int main()
{
   std::cout << "Hello World" << std::endl;
   return 0;
}


Compile line (MinGW_w64)
g++ main.cpp func1.cpp func2.cpp -o main.exe -std=c++11

I would have thought that it would not matter that the func1.cpp and func2.cpp files have functions with the same name in each file (as they have no "visibility" of each other), but the linker does not agree. What am I missing here?
The property you're looking to control is called linkage.
https://en.cppreference.com/w/cpp/language/storage_duration

Either declare and define func() within an anonymous unnamed namespace
namespace { void Func() {} }
Or use the storage-class specifier static:
static void Func() {}

To confer internal linkage. This effectively limits Func() to the translation unit.
Last edited on
Ahh thank you so much mbozzi - static was what I needed. Somehow I've never come across issues with linkage like this before. Never too old to learn new ways of making mistakes I guess :)
Topic archived. No new replies allowed.