开发者

How to generate compile time errors?

I would like to be able to do something like this:

   void f(int*p = nullptr)
    {
    if (!p)
{
//HERE I WOULD LIKE TO HAVE AN MSG THAT WOULD BE DISPLAYED DURING COMPILATION AS A WARNING POSSIBLY
}
    }
开发者_开发技巧


To generate a compile time warning based on a runtime check, simply create a file called "warning.c" that contains an unused variable declaration. You can then generate warnings like that:

void f(int *p = nullptr) {
    if (!p) {
        system("gcc -Wall warning.c");
    }
}


The correct answer is: What you're trying to do won't ever work.


Most, if not all, compilers support the #error and #warning preprocessor directives.

Microsoft's compiler, though, uses #pragma message() instead of #warning.


Google #if #endif and #error preprocessor directives. It won't be possible to generate compile error based on the value of a variable that is not available at compile time, so forget about it. Use assert().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜