Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Consider following source files 1.cpp

#include <iostream>

using namespace std;

struct X
{
    X()
    {
        cout << "1" << endl;
    }
};

void bar();

void foo()
{
    X x;
}

int main()
{
    foo();
    bar();
    return 0;
}

2.cpp

#include <cstdio>

struct X
{
    X()
    {
        printf("2
");
    }
};

void bar()
{
    X x;
}

Is program compiled from these files well-formed? What should be in it's output?

I've expected linker error due to violation of One Definition Rule or output "1 2". However it prints out "1 1" when compiled with g++ 3.4 and VC 8.0.
How this can be explained?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
513 views
Welcome To Ask or Share your Answers For Others

1 Answer

This does violate ODR (3.2) - specifically that you can have more than one definition of an inline function, but those definitions must be identical (3.2/5) - and leads to undefined behavior, so anything may happen and the compiler/linker is not required to diagnose that. The most likely reason why you see that behavior is that function calls are inlined and do not participate in linking, so no link error is emitted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...