【问题标题】:Avoid casting from volatile static uint8_t to uint8_t in function calls?避免在函数调用中从 volatile static uint8_t 转换为 uint8_t?
【发布时间】:2009-09-24 18:39:59
【问题描述】:

我目前有这个代码:

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 );  
}

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

【问题讨论】:

  • 哪个编译器会为此给出错误? VS2005 和我过时的 cygwin gcc 编译这个没有问题。
  • 请注意:uint8_t 不需要存在于所有 C99 实现中,即使在 #includ'ing 之后也是如此

标签: c arguments volatile


【解决方案1】:

我猜您正在尝试将指针传递给变量,并且在编辑您的问题时,您删除了指针声明以简化,但这也改变了您的问题。如果您将值传递给函数,则没有任何问题。

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

【讨论】:

    【解决方案2】:

    您不必显式转换。第二种形式对于任何符合标准的 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 );  
    }
    

    【讨论】:

      【解决方案3】:
      #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 为我编译的。 (我必须实际定义函数,并包含头文件。)

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 1970-01-01
        • 2011-12-10
        • 2017-08-15
        • 2015-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多