C++ 使用extern const函数初始化const

C++ 使用extern const函数初始化const,c++,c,c++11,arduino,C++,C,C++11,Arduino,常量的初始化在不同的平台上产生不同的结果。我在Arduino UNO(AVR)上得到了预期的结果,在Arduino Due(Cortex M-3)上得到了意外的结果。 这就是我问题的本质: const_problem.ino: typedef struct{ int x; } my_type_t; my_type_t init_my_type0(void); my_type_t init_my_type1(void); my_type_t init_my_type2(void); sta

常量的初始化在不同的平台上产生不同的结果。我在Arduino UNO(AVR)上得到了预期的结果,在Arduino Due(Cortex M-3)上得到了意外的结果。 这就是我问题的本质:

const_problem.ino:

typedef struct{
  int x;
}
my_type_t;

my_type_t init_my_type0(void);
my_type_t init_my_type1(void);
my_type_t init_my_type2(void);

static const my_type_t my_type_0=init_my_type0();
static const my_type_t my_type_1=init_my_type1();
static const my_type_t my_type_2=init_my_type2();

void setup() {
  Serial.begin(9600);

  Serial.print("my_type_0.x: ");
  Serial.println(my_type_0.x);//5
  Serial.print("my_type_1.x: ");
  Serial.println(my_type_1.x);//ARDUINO DUE (CORTEX M-3): 0, Arduino UNO (AVR): 5 
  Serial.print("my_type_2.x: ");
  Serial.println(my_type_2.x);//5

  const my_type_t my_type_3=init_my_type1();
  Serial.print("my_type_3.x: ");
  Serial.println(my_type_3.x);//5
}

void loop() {}
常数c:

const int some_constant = 5;
utils.cpp:

extern "C"{
extern const int some_constant;
}

static const int  some_constant_copy =  some_constant;
static const int *some_constant_p    = &some_constant;

typedef struct{
  int x;
}
my_type_t;

my_type_t init_my_type0(void){
    return (my_type_t){some_constant};
}

my_type_t init_my_type1(void){
    return (my_type_t){some_constant_copy};
}

my_type_t init_my_type2(void){
    return (my_type_t){*some_constant_p};
}

我期望函数init_my_type1为5,但我得到的值为0(仅在一个平台上,并且仅适用于filescope常量)。为什么会这样?

您可能需要在头文件中添加外部“C”,或者,如果不可能,在包含以下内容的周围添加外部“C”:

extern "C" {
#include "myheaderfile.h"
}
除此之外,您可以尝试只运行预处理器并查看输出;也许这不是你所期望的。如果您使用的是gcc

g++ -I include_path -E abstract.cpp

希望对您有所帮助。

注意:
静态常数计时器分割器设置t位周期=计时器分割器设置计算(0,LN位周期)
不是C中的“在编译时使用函数初始化常量结构”。可能是C扩展?“无论目标平台是什么,我都希望它是一样的。”这不是C的认证。Extern“C”没有帮助。我找不到在arduino中查看预处理器输出的方法(我没有这个平台的选择)。我在自己周围找到了一份工作。