llohse / libnpy

C++ library for reading and writing of numpy's .npy files
MIT License
361 stars 72 forks source link

duplicate symbol under GCC-10 #19

Closed caic99 closed 2 years ago

caic99 commented 2 years ago

In my project, we include npy.hpp in different source files, generate .o files, and link them together. However, gcc-10 defaults to -fno-common . This part is raising duplicate symbol error while linking https://github.com/llohse/libnpy/blob/b67016355374fe29d75430842d72865f99e3f697/include/npy.hpp#L131

To reproduce: case.zip Based on libnpy/tests, split test.cpp into 3 cpp files, each containing one function, i.e. load, save, and main. Compile with g++-10 -c, and link. The linker generates:

duplicate symbol 'npy::has_typestring::dtype' in: test_load.o test_save.o duplicate symbol 'npy::has_typestring::dtype' in: test_load.o test_save.o ...

for each has_typestring<T>.

drelatgithub commented 2 years ago

This indeed invokes odr-violation in C++11 because of the namespace scope definition of has_typestring<T>::dtype being included in multiple TUs. This should no longer be an issue in C++17, because constexpr static members are implicitly inline, which no longer requires namespace scope definitions.

@caic99 I do not know how to properly resolve this in C++11 without splitting the definition into a .cpp file, but if your project happen to use C++17 that will not be an issue.

llohse commented 2 years ago

Apologies for the late reply. I was afraid that this "hack" would cause trouble some day...

My preferred way to fix this would be to change has_typestring::dtype from being static constexpr to being const and initialized by the class constructor.

I have to think about this a little further.

llohse commented 2 years ago

@caic99 : could you have a look at #21 ?