How to solve duplicated symbol problems in C++

Problem

When compiling a program which sources sharing a same headers, for example, SWYAKL, there is possibility that error of duplicated symbol will appear during link stage.

For me, this problem is because SWYAKL is a header-only library, C++ compiler's preprocessor will expand headers to every source files include this header, so a function named yakl::yakl_std_wrapper::round had been added to top of every source files, and caused this error.

Solution

Duplicated symbol error cannot be avoid by using header guard or #pragma once, because these function only tell compiler to compiler your source once, but will take no effect on avoid duplicated symbols be generated by compiler.

To solve this problem, the easiest way is change this function into an inline function.

1
2
3
4
5
6
7
8
9
10
11
12
13
// original version
namespace yakl {
namespace yakl_std_wrapper {
double round(double x); // In some condition, this will cause duplicated symbol error
}
}

// fixed version
namespace yakl{
namespace yakl_std_wrapper {
inline double round(double x); // This will not cause duplicated symbol error
}
}

How to solve duplicated symbol problems in C++
http://anyin233.github.io/2024/01/19/How to solve duplicated symbol problems in C++/
Author
anyin233
Posted on
January 19, 2024
Licensed under