Search code examples
c++cmakelinkerlinker-errorsduplicate-symbol

I am expecting to get duplicate symbol linker error but I don't get it, why?


As far as I know if I define a function in a header file and include that header file in multiple source files(translation units), and link them together I should get duplicate symbol linker error. However I don't get that error having the following files. Could you please explain me what I'm missing here. Thanks in advance.

// include/library.hpp

#ifndef INCLUDE_LIBRARY_HPP
#define INCLUDE_LIBRARY_HPP

int add(int a, int b) {
    return a + b;
}

#endif //INCLUDE_LIBRARY_HPP

// user1.cpp

#include "include/library.hpp"

void doSomething() {
    int result = add(10, 20);
}
// user2.cpp

#include "include/library.hpp"

int main() {
    int result = add(5, 3);
    return 0;
}

# CMakeLists.txt

cmake_minimum_required(VERSION 3.25)
project(proj)

set(CMAKE_CXX_STANDARD 17)

add_library(lib INTERFACE include/library.hpp)

add_library(first_user user1.cpp)
target_link_libraries(first_user PUBLIC lib)

add_executable(second_user user2.cpp)
target_link_libraries(second_user PUBLIC lib first_user)

Solution

  • Since in your application (which consists only of main) you did not call doSomething, the linker is free to remove the object code to doSomething from the executable. Thus you did not get the duplicate symbol linker error.

    Once you added the call to doSomething in main (plus probably call add also), you now get the duplicate symbol error.

    Note that linkers will (or should) remove unused object code as a way to reduce the size of the resulting executable file.