Is it safe to link gcc 6, gcc 7, and gcc 8 objects?

前端 未结 2 560
梦如初夏
梦如初夏 2021-02-01 06:29

Is it safe to link C++17, C++14, and C++11 objects asks about linking objects compiled with different language standards, and Jonathan Wakely\'s excellent answer on that questio

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-01 07:09

    Most of the language ABI changes seem like they wouldn't cause issues, but the calling convention change for empty class types in 12 might?

    The change of the calling convention for empty classes can cause an issue on x86-64. Here's an example:

    def.hpp:

    struct Empty { };
    
    struct Foo {
        char dummy[16];
        int a;
    
        Foo() : a(42) { }
    };
    
    void fn(Empty, Foo);
    

    one.cpp:

    #include "def.hpp"
    
    int main() {
        fn(Empty(), Foo());
    }
    

    two.cpp:

    #include 
    #include "def.hpp"
    
    void fn(Empty e, Foo foo) {
        printf("%d\n", foo.a);
    }
    

    Now, if you compile these with G++ 8 with differing ABIs of 11 and 12, for example:

    g++ -c -fabi-version=11 one.cpp
    g++ -c -fabi-version=12 two.cpp
    g++ one.o two.o
    

    the resulting a.out won't print the expected 42.

    The reason is that the old ABI (11) reserves space for Empty() on the stack, but the new ABI (12) doesn't. So the address of foo will differ between the caller and the callee side.

    (Note: I've included Foo::dummy so Foo gets passed using the stack instead of registers. If Foo was passed using registers, there would be no problem.)

提交回复
热议问题