c&cpp中的#error用法

我与影子孤独终老i 提交于 2020-02-10 11:01:38

在c或者c++中,可以通过#error来实现编译期的报错功能,看下面一个示例:

#if defined(F_FULLFSYNC)
    /*
      In Mac OS X >= 10.3 this call is safer than fsync() (it forces the
      disk's cache and guarantees ordered writes).
    */
    if (!(res= fcntl(fd, F_FULLFSYNC, 0)))
      break; /* ok */
    /* Some file systems don't support F_FULLFSYNC and fail above: */
    DBUG_PRINT("info",("fcntl(F_FULLFSYNC) failed, falling back"));
#endif
#if defined(HAVE_FDATASYNC) && HAVE_DECL_FDATASYNC
    res= fdatasync(fd);
#elif defined(HAVE_FSYNC)
    res= fsync(fd);
#elif defined(_WIN32)
    res= my_win_fsync(fd);
#else
#error Cannot find a way to sync a file, durability in danger
    res= 0;					/* No sync (strange OS) */
#endif

这是MySQL源码中函数my_sync的部分代码,它的是要目的是就进行数据的落盘操作,如果发现操作系统不支持fdatasync,也不支持fsync,同时也不是windonws系统的话,则没办法去调用对应的系统函数,在编译期就可以报错。自己写个示例:

#include <iostream>
#error no way

int main()
{
	return 0;
}
ashe@AsheMacHome:/dbdata/test/cpp $ g++ test.cc
test.cc:2:2: error: no way
#error no way
 ^
1 error generated.

大部分时候都是配合条件编译来用的,这里只是看下报错信息。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!