C ++等效于指定初始化? [英] C++ Equivalent to Designated Initializers?

查看:93
本文介绍了C ++等效于指定初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我一直工作在一些嵌入式设备,在这里我们有一些结构,并需要在编译时初始化,以便我们能够保持在闪存或ROM某些事情不需要修改工会,和节省一点闪存或SRAM在位性能的成本。目前,code编译为有效C99,但没有这种调整它用来编译为C ++ code,以及,正在编译这种方式也将是巨大的支持的事情。其中一个是prevents关键的事情,这是我们使用C99指定初始化不C ++中的C子集内工作。我没有太大的C ++的buff,所以我不知道有什么简单的方法,有可能是实现这一目标用C ++兼容C或C ++中仍然允许初始化在编译时,这样的结构和联合不一定是在SRAM程序启动后初始化。

Recently I've been working on some embedded devices, where we have some structs and unions that need to be initialized at compile time so that we can keep certain things in flash or ROM that don't need to be modified, and save a little flash or SRAM at a bit of a performance cost. Currently the code compiles as valid C99, but without this adjustment it used to compile as C++ code as well, and it would be great to support things being compiled that way as well. One of the key things that prevents this is that we're using C99 designated initializers which do not work within the C subset of C++. I'm not much of a C++ buff, so I'm wondering what simple ways there might be to make this happen in either C++ compatible C, or in C++ that still allow initialization at compile time so that the structs and unions not need be initialized after program startup in SRAM.

一个值得注意的另外一点:对指定的初始化使用的一个关键原因是作为initalizing不是工会的第一个成员。另外,与标准的C ++或ANSI C坚持是为了保持与其它编译器兼容一个加号(我知道的GNU扩展,提供类似指定初始化没有C99)。

One additional point of note: a key reason for designated initializer usage is initalizing as NOT the first member of a union. Also, sticking with standard C++ or ANSI C is a plus in order to maintain compatibility with other compilers (I know about the GNU extensions that provide something like designated initializers without C99).

推荐答案

我不知道你能做到这在C ++中。对于需要使用指定的初始化程序初始化的东西,你可以编译成一个C99 .C 文件,例如把这些分开:

I'm not sure you can do it in C++. For the stuff that you need to initialize using designated initializers, you can put those separately in a .c file compiled as C99, e.g.:

// In common header file
typedef union my_union
{
    int i;
    float f;
} my_union;

extern const my_union g_var;

// In file compiled as C99
const my_union g_var = { .f = 3.14159f };

// Now any file that #include's the header can access g_var, and it will be
// properly initialized at load time

这篇关于C ++等效于指定初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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