【实用工具】pragma的应用

523 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第12天,点击查看活动详情

【实用工具】pragma的应用

pragma

gcc Diagnostic

这个参数主要是为了让用户可以自由的选择开启或者关闭一些某些类型诊断。,比如将某些源文件warning诊断为error,即关闭Werror,而另外的一些将warning诊断为error,即使能Werror,都可以通过gcc -diagnostic来设置。

#pragma GCC diagnostic kind option

    #pragma GCC diagnostic warning "-Wformat"
    #pragma GCC diagnostic error   "-Wformat"
    #pragma GCC diagnostic ignored "-Wformat"
  • kind

    • error:将这个诊断当作错误处理
    • warning:将这个诊断视为warning级别,即使-Werror生效也会被屏蔽。
    • ignored:这个诊断会被忽略。
  • option 用于修改诊断类型,但不是所有的诊断都可以被修改,目前只支持warning级别被修改,即前缀是-W...的,比如-Wformat

#pragma GCC diagnostic push/pop

使得gcc可以诊断可以记住每次push时的状态,并且在pop时恢复到改状态。如果pop没有对应的push状态,就会恢复到命令行选项。

     #pragma GCC diagnostic error "-Wuninitialized"
         foo(a);                       /* error is given for this one */
     #pragma GCC diagnostic push
     #pragma GCC diagnostic ignored "-Wuninitialized"
         foo(b);                       /* no diagnostic for this one */
     #pragma GCC diagnostic pop
         foo(c);                       /* error is given for this one */
     #pragma GCC diagnostic pop
         foo(d);                       /* depends on command-line options */

#pragma message string

     #pragma message "Compiling " __FILE__ "..."

打印编译信息string,这个既不是warning也不是error,仅仅是用于提示信息,比如上述正在编译某一个文件。

#pragma GCC [error/warning/ignored] message

  • error:将诊断判定为错误
  • warning:将诊断判断为警告
  • ignored:忽略改诊断

#pragma GCC error message

产生一个错误信息:The error is only generated if the pragma is present in the code after pre-processing has been completed.

  • 有条件报错

         void foo(int x) {
             std::cout<<"foo.\n"<<std::endl;
         }
     ​
         #pragma GCC diagnostic error "-Wuninitialized"  foo(x);
     ​
         int main(int argc, char const *argv[]) {
             int x;
             foo(x);
             
             return 0;
         }
    

    由于变量x没有初始化,编译后:

     $ g++ pragma_.cc 
     pragma_.cc: In function ‘int main(int, const char**)’:
     pragma_.cc:13:8: error: ‘x’ is used uninitialized in this function [-Werror=uninitialized]
         foo(x);
         ~~~^~~
     cc1plus: some warnings being treated as errors
    
  • 无条件报错

         #if 0
             #pragma GCC error "this error is not seen"
         #endif
     ​
         void foo (void) {
             return;
             #pragma GCC error "this error is seen"
         }
    

    编译后,直接报错

     $ g++ pragma_.cc 
     pragma_.cc:11:23: error: this error is seen
         #pragma GCC error "this error is seen"
                         ^~~~~~~~~~~~~~~~~~~~
    

#pragma GCC warning message

类似上一个,只是产生warning。但是如果设置了-Werror,那么就会产生错误。