I have the following source files:
//test1.cpp
#include <iostream>
using namespace std;
inline void foo()
{
cout << "test1's foo" << endl;
}
void bar();
int main(int argc, char *argv[])
{
foo();
bar();
}
and
//test2.cpp
#include <iostream>
using namespace std;
inline void foo()
{
cout << "test2's foo" << endl;
}
void bar()
{
foo();
}
The output:
test1's foo
test1's foo
Huh??? Ok, so I should have declared the foos static… but shouldn’t this kind of thing generate a linker error, or at least a warning? And how does the compiler “see” the inline functions from across compilation units?
EDIT: This is using gcc 4.4.1.
You are running into the one-definition-rule. You are not seeing any error because:
What going on under the covers is that the compiler is not inlining those functions (many compilers will not inline a function unless the code is compiled with the optimizer). Since the function is inline and can appear in multiple translation units, the compiler will mark the function as link-once which tells the linker that it not treat multiple definitions as an error but just use one of them.
If you really want them to be different, you want a static function.