跳转至

开源代码编码常用技巧

1 do{...}while (0) 的意义和用法

2 (void) val 的意义和用法

  • 功能:在不使用函数的参数时,使用void修饰参数可以使编译器不警告
  • 示例
int fun(int a)
{
   (void)a;
   return 0;
}

3 include 实现文件

  • 作用:通常用于既可以将实现与声明分开(动态库场景),又可以实现和声明在同一个头文件(便于使用者直接包含头文件,而不需要链接动态库)。

    一下以 asio 中类 endpoint 实现代码来讲解

  • endpoint. hpp 文件
class endpoint
{
... 省略
  ASIO_DECL endpoint(int family,
      unsigned short port_num) ASIO_NOEXCEPT;
... 省略
}

#if defined(ASIO_HEADER_ONLY)
# include "asio/ip/detail/impl/endpoint.ipp"
#endif // defined(ASIO_HEADER_ONLY)
  • endpoint.ipp
endpoint::endpoint(int family, unsigned short port_num) ASIO_NOEXCEPT
  : data_()
{
... 省略
}
  • ASIO_HEADER_ONLY 定义如下
// Default to a header-only implementation. The user must specifically request
// separate compilation by defining either ASIO_SEPARATE_COMPILATION or
// ASIO_DYN_LINK (as a DLL/shared library implies separate compilation).
#if !defined(ASIO_HEADER_ONLY)
# if !defined(ASIO_SEPARATE_COMPILATION)
#  if !defined(ASIO_DYN_LINK)
#   define ASIO_HEADER_ONLY 1
#  endif // !defined(ASIO_DYN_LINK)
# endif // !defined(ASIO_SEPARATE_COMPILATION)
#endif // !defined(ASIO_HEADER_ONLY)