gpt4 book ai didi

调用需要 const char8 string[] 作为参数的 c 函数的正确方法

转载 作者:行者123 更新时间:2023-11-30 14:39:33 25 4
gpt4 key购买 nike

在微 Controller 的 ISR 中,我尝试按如下方式调用函数:

//adc.c
static volatile char uartBuf[6]={0};

CY_ISR(ISR_ADC)
{

for (uint8_t i=0; i < NS; i++)
total += adc2_buffer0[i];

uartBuf[0] = total >> 24 & 0xFF;
uartBuf[1] = total >> 16 & 0xFF;
uartBuf[2] = total >> 8 & 0xFF;
uartBuf[3] = total & 0xFF;
uartBuf[4] = '\n';
UART_1_PutString(uartBuf); //doesn't work
}

//uart.c
void UART_1_PutString(const char8 string[])
{
...
}

但是在函数UART_1_PutString中,string总是指向'\0'而不是uartBuf?可能是什么问题呢?理论上来说,变量 uartBuf 不应该被编译器优化掉。

最佳答案

代码看起来正确

你的意思是string[0] == '\0'吗?

也许 (total >> 24 & 0xFF) == 0 总是(或大多数时候)。

编辑:

该函数应该是

void UART_1_PutString(const volatile unsigned char buff[]);

它不应该被称为字符串,因为它不是文本,它只是一个缓冲区(至少看起来像)。

unsigned 因为“字符串”来自一些数学运算后的一些无符号位操作,这可能会导致无效的有符号值(不太可能失败,但规则应该是:char 表示文本,unsigned char 表示未知数据(其他所有数据)。

volatile ,因为如果不是,您将丢弃 volatile 限定符。具有足够高标志的编译器(在 GCC 中:-Wall -Wextra -Werror 会将几乎所有内容突出显示为错误)会对此发出警告。即使在知道您将使用 volatile 数据调用函数之前,编译器也可能认为该函数的内容可以被简化,因此会优化一些不应该优化的东西。

如果没有其他函数同时访问该缓冲区,您还可以添加 restrict 关键字 (C11),以便帮助编译器生成更好的代码:

void UART_1_PutString(const volatile unsigned char buff[restrict]);

编辑2:

如果仅使用该缓冲区调用缓冲区,则应声明缓冲区的大小,否则也应将缓冲区的大小传递给函数:

void UART_1_PutString(const volatile unsigned char buff[restrict 6]);

(6 可能应该被某些宏替换)或

void UART_1_PutString(size_t size, const volatile unsigned char buff[restrict size]);

关于调用需要 const char8 string[] 作为参数的 c 函数的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56046578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com