Разрешено ли смешивание C++11 и C++20 с помощью gcc?C++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 Разрешено ли смешивание C++11 и C++20 с помощью gcc?

Сообщение Anonymous »


I declare a struct in a header file. I use this struct in two compilation units. One is compiled with -std=c++11 and the other with -std=c++20. The sizeof my struct is different in the two compilation units.
Is it allowed to mix any -std=c++20 and -std=c++11 code or am I using gcc the wrong way ?
These answers do not tell if it's expected to work.
  • I'm not using two different version of « the same » compiler (Can you mix c++ compiled with different versions of the same compiler).
  • I'm not mixing two incompatible versions of the standard in my code, as far as I know (Mixing different C++ standards with GCC).
  • I'm not using libraries, including standard libraries (except for displaying the results, but that's not where the problem lies) (Is it safe to link C++17, C++14, and C++11 objects).
I'm using gcc (Debian 10.2.1-6) 10.2.1 20210110 on Debian 11. I wonder if this version of gcc has a bug.
Code demonstrating the problem :

Код: Выделить всё

$ cat 1.h
#ifndef DEF1
#define DEF1

#include "c.h"
void f1(C* c);
C* g1();
#endif
$ cat 2.h
#ifndef DEF2
#define DEF2

#include "c.h"
void f2 (C* c);
C* g2();
#endif
$ cat 1.cpp
#include "c.h"
#include 

void f1 (C* c)
{
printf("sizeof(C)=%ld\n", sizeof(C));
printf("i2=%d\n", c->i2);
printf("&i2-&i1=%ld\n", ((char*)&c->i2) - ((char*)&c->i1));
}

C* g1()
{
C* c = new C;
c->i2 = 1;
return c;
}
$ cat 2.cpp
#include "c.h"
#include 

void f2 (C* c)
{
printf("sizeof(C)=%ld\n", sizeof(C));
printf("i2=%d\n", c->i2);
printf("&i2-&i1=%ld\n", ((char*)&c->i2) - ((char*)&c->i1));
}

C* g2()
{
C* c = new C;
c->i2 = 2;
return c;
}

$ cat c.h
#ifndef CDEF
#define CDEF

#include 

struct A
{
double d1{0.0};
double d2{0.0};
double d3{0.0};
double d4{0.0};
double d5{0.0};
double d6{0.0};
double d7{0.0};
int32_t i1{};
};

#ifdef DER
struct C : public A
{
int32_t i2{};
};
#else
struct C
{
double d1{0.0};
double d2{0.0};
double d3{0.0};
double d4{0.0};
double d5{0.0};
double d6{0.0};
double d7{0.0};
int32_t i1{};
int32_t i2{};
};
#endif
#endif
$ cat main.cpp
#include "c.h"
#include "1.h"
#include "2.h"

int main()
{
f1(g2());
f2(g1());
}
$ cat bar.sh
g++ -std=c++20 -DDER -c 2.cpp
g++ -std=c++11 -DDER -c 1.cpp
g++ -std=c++20 -DDER -c main.cpp
g++ -std=c++20 2.o 1.o main.o -o prog
./prog
$ ./bar.sh
sizeof(C)=64
i2=0
&i2-&i1=4
sizeof(C)=72
i2=0
&i2-&i1=8


Источник: https://stackoverflow.com/questions/781 ... d-with-gcc
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»