GCC C++ (ARM) 和指向结构域的 const 指针 [英] GCC C++ (ARM) and const pointer to struct field

查看:33
本文介绍了GCC C++ (ARM) 和指向结构域的 const 指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个简单的测试代码

Let's say there is a simple test code

typedef struct
{
    int first;
    int second;
    int third;
} type_t;

#define ADDRESS 0x12345678

#define REGISTER ((type_t*)ADDRESS)

const int data = (int)(&REGISTER->second)*2;

int main(void)
{
    volatile int data_copy;

    data_copy = data;

    while(1) {};
}

在 CodeSourcery G++ (gcc 4.3.2) 中为裸机 ARM 编译.它还有一个非常标准的链接描述文件.

Which is compiled in CodeSourcery G++ (gcc 4.3.2) for bare metal ARM. It also has a very standard linker script.

当用 C 编译(如 main.c)时,对象数据"按预期进入 Flash.当用 C++(作为 main.cpp)编译时,这个对象进入 RAM,并添加额外的代码,它只是将值从闪存复制到 RAM(该值已经计算,只需复制!).所以编译器可以计算地址,但不知何故不想只是使用它".问题的根源是地址的乘法——没有*2"乘法,两个版本都按预期工作——数据"被放置在闪存中.另外——当数据"被声明为:

When compiled in C (as main.c) the object "data" goes into Flash, as expected. When compiled in C++ (as main.cpp) this object goes into RAM, and additional code is added which does nothing more than copy the value from Flash to RAM (the value is already calculated, just copy!). So the compiler can calculate the address, but somehow doesn't want to "just use it". The root of the problem is the multiplication of the address - without "*2" multiplication both versions work as expected - "data" is placed in Flash. Also - when "data" is declared as:

const int data = (int)(REGISTER)*2;

也一切都很好.

C 和 C++ 编译的所有文件都是相同的,唯一的区别是对编译器的调用 - main.cpp 为 g++,main.c 为 gcc(警告级别不同,并且 c++ 禁用了 RTTI 和异常).

All files for C and C++ compilation are identical, the only difference is the call to compiler - g++ for main.cpp, gcc for main.c (with differences in the level of warnings, and c++ has RTTI and exceptions disabled).

有什么简单而优雅的方法可以克服这个C++ 问题"?我确实需要这样的操作来在 Cortex-M3 的位带区域中创建位地址的常量数组.这是一个错误,还是 C++ 编译器的一些奇怪限制?

Is there any easy and elegant way to overcome this "C++ problem"? I do require such operations for creating const arrays of addresses of bits in bitband region of Cortex-M3. Is this a bug, or maybe that is some strange limitation of the C++ compiler?

我知道我可以在C"文件中创建数据对象,而只是extern"——将它们包含在 C++ 中,但这不是很优雅 [;

I know that I can create data objects in "C" files and just "extern"-include them in C++, but that's not very elegant [;

谢谢大家的帮助!

推荐答案

正确的解决方案是使用 offsetof() 宏.

The right solution is using the offsetof() macro from the stddef.h header.

基本上是这样:

const int data = (int)(&REGISTER->second)*2;

必须替换为

#include <stddef.h>
const int data = (int)(REGISTER + offsetof(type_t,second))*2;

然后将对象放置在 Flash 中,用于 C 和 C++.

And then the object is placed in Flash both for C and C++.

这篇关于GCC C++ (ARM) 和指向结构域的 const 指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆