On Mon, 7 Oct 2024 at 15:08, R. Diez <rdiez-2006@xxxxxxx> wrote: > > First of all, thanks for your quick answer. > > > [...] > > (Why are you using 'static inline' on the non-template functions > > in the first place? Why not just 'inline'?) > > Actually, I am not. I normally use 'inline' in headers and 'static' in > .cpp files. I just wanted to simplify the example, but I shouldn't have. > > I'll rephrase the takeaway, to check whether I understood this correctly: > > - 'inline' just makes the template function more likely to be inlined, but > it is not required in a header file, like it is usually required for normal > functions in order to prevent redefinition errors. > Right > > - 'static' has the same effect for templates as for normal functions, and > can be problematic in header files, especially if the template or function > has static variables inside. > Right again. > > Incidentally, I wonder how the linker detects and merges duplicate > templates, or even duplicate normal inline functions. See https://gcc.gnu.org/onlinedocs/gcc/Vague-Linkage.html > The template or inline function could have different bodies in different > compilation units. That would not be a valid C++ program, see https://eel.is/c++draft/basic.def.odr#15 > A simplified example would be: > > file1.cpp: > > inline int test ( void ) > { return 1; } > > file2.cpp: > > inline int test ( void ) > { return 99999; } > > I read somewhere that the standard does not require detecting the above > problem. Correct, it's "ill formed; no diagnostic required". > Will GCC or the linker detect this problematic case? > GCC detects some ODR violations when using Link-Time Optimization, but I don't think it detects this case. The GNU Gold linker can detect some other ODR violations with --detect-odr-violations but I don't think it detects this case either. That's why you should define inline functions in headers and include them everywhere they're needed, not (re)define them in the .cpp files with possibly incompatible definitions.