I've spent days in a weird problem and finally discover that there were two inline
function of the same signature in the project and they caused the problem. To simplify the situation here is an example: two cpp file:
a.cpp
#include <iostream>
void b();
inline void echo()
{
std::cout << 0 << std::endl;
}
int main()
{
echo();
b();
return 0;
}
and b.cpp
#include <iostream>
inline void echo()
{
std::cout << 1 << std::endl;
}
void b()
{
echo();
}
Please note that inline
functions echo
have the same signature but different implements. Compile and run
g++ a.cpp b.cpp -o a.out && ./a.out
Or like this
g++ a.cpp -c
g++ b.cpp -c
g++ a.o b.o -o a.out
./a.out
It prints 0 0
. (I was using g++ 4.6.1 for that, and I tested with clang++ 2.9, same result)
That won't happen if turning on optimization, like
g++ -O3 a.cpp b.cpp -o a.out && ./a.out
It is 0 1
this time.
My question is, no matter the result or how the compilation performs, there is no error or even warning about I have defined inline
functions multiple times. What on earth happens to the compiler and linker in this kind of situation?
EDIT:
Take a look at the symbols in the object file
nm a.o b.o | c++filt
Both files have the record echo()
. So I think the problem happens at the link time. Could it be said that the linker randomly picks one implementation and discard all other?
-Wall -Wextra
, still no warning. – Coprolalia