为什么我不能将函数返回的结构分配给结构?

Kam*_*mil -2 c stm32 c11 cortex-m arm-none-eabi-gcc

我编写了“轻量级”时间库,并且有如下所示的 struct 和 typedef:

struct tmt {
    uint16_t year;
    uint8_t month;
    uint8_t day;
    uint8_t hour;
    uint8_t minute;
    uint8_t second;
    uint8_t weekday;
    uint8_t is_dst; 
};

typedef struct tmt tm_t;
Run Code Online (Sandbox Code Playgroud)

我有一个返回的函数tm_t

tm_t rtc_get_current_time(void){
    tm_t tm;
    xSemaphoreTake(rtc_mutex, RTC_MUTEX_MAX_WAIT);
    tm = rtc.current_time;
    xSemaphoreGive(rtc_mutex);
    return tm;
}
Run Code Online (Sandbox Code Playgroud)

我想这样使用它:

tm_t s;
s = rtc_get_current_time();    // error is here
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

从类型“int”分配给类型“tm_t”{aka“struct tmt”}时不兼容的类型


我也尝试过像这样更改函数和变量:

struct tmt rtc_get_current_time(void){
    tm_t tm;
    xSemaphoreTake(rtc_mutex, RTC_MUTEX_MAX_WAIT);
    tm = rtc.current_time;
    xSemaphoreGive(rtc_mutex);
    return tm;
}

struct tmt tm = rtc_get_current_time();
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Rem*_*eau 5

编译器抱怨您试图将 an 分配int给 a tm_t,但由于您实现rtc_get_current_time()为返回 a tm_t,这意味着编译器认为rtc_get_current_time()返回的是 anint而不是 a tm_t

rtc_get_current_time()如果尚未在调用它的上下文中声明,则可能会发生这种情况。C 语言允许在没有事先声明的情况下调用函数,但最终编译器会假设该函数有一个默认声明,并且该默认值用作int返回类型。在这种情况下你不希望这样。

您需要rtc_get_current_time()在调用之前声明。

  • 关于“C 语言允许在没有事先声明的情况下调用函数……”:隐式函数声明已从 2011 版本的 C 标准中删除。未声明的标识符违反了语言语法(C 2018 note 94),因此一致的声明必须对其进行诊断。 (2认同)