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

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

问题描述

比方说,有一个简单的测试code

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中)对象数据进入闪存,符合市场预期。当用C ++编译(如main.cpp中),这个对象进入RAM,和额外的code加入其中确实不外乎复制从Flash的价值到RAM(该值已计算,只需复制!)。所以编译器可以计算地址,但不知何故不希望刚
使用问题的根源是地址的乘法 - 没有。* 2乘两个版本按预期工作 - 数据 - 被声明为被放置在Flash中时也是如此。

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 ++编译所有文件是相同的,唯一的区别是调用编译器 - G ++的main.cpp中,海湾合作委员会的main.c(用警告的级别差异,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的bitband地区创造位的地址常量数组。这是一个bug,或者是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文件创建数据对象,只是外部,在C ++ -Include他们,但是这不是很优雅[;

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()从STDDEF.H头宏。

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天全站免登陆