避免在函数调用中从volatile静态uint8_t转换为uint8_t?

时间:2009-09-24 18:40:00

标签: c arguments volatile

我目前有这段代码:

static void func( uint8_t var );

static volatile uint8_t foo;

int main() {  
 /* Here we have to cast to uint8_t */  
 func( (uint8_t) foo );

 /* This will not compile */  
 func( foo );  
}

有没有办法避免函数调用中的强制转换?

3 个答案:

答案 0 :(得分:4)

我猜你试图传递一个指向变量的指针,在编辑你的问题时,你删除了指针声明以简化,但这也改变了你的问题。如果要将值传递给函数,则没有任何问题。

现在,如果要传递指针,volatile修饰符会告诉编译器应该期望变量的值通过编译后的代码以外的方式进行更改。你真的不应该将volatile变量作为非易失性参数传递给函数。必须将函数本身更改为具有volatile参数,然后重新编译。然后准备函数(使用volatile参数)来处理volatile变量。

答案 1 :(得分:0)

您不必明确施放。第二种形式对任何符合标准的C编译器都是完全有效的。

这只是你需要施展的东西:

static void func( uint8_t *var );

static volatile uint8_t foo;

int main() {  
 /* Here we have to cast to uint8_t */  
 func( (uint8_t*) &foo );

 /* This will not compile */  
 func( &foo );  
}

答案 2 :(得分:0)

#include <stdint.h>

static void func( uint8_t var ){}

static volatile uint8_t foo;

int main() {
    /* Here we have to cast to uint8_t */
    func( (uint8_t) foo );

    /* This will not compile */
    func( foo );
}

这使用gcc为我编译。 (我必须实际定义函数,并包含头文件。)