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)