0%

C++ 预处理

预定义宏

#if defined(__linux)
#ifdef LINUX2

C标准预定义宏

  • __LINE__
  • __func__
  • __FILE__
  • NDEBUG:参考_DEBUG和NDEBUG的区别,其中,_DEBUG是Visual Studio定义的,NDEBUG是C/C++标准。

GNU C预定义宏

官方文档

  • __COUNTER__: 扩展为从0开始的连续整数值,每次在源码中出现,则加1。不同源文件的__COUNTER__互不影响。

    可以用来生成唯一的命名。
    参考链接

    1
    2
    3
    4
    5
    6
    7
    8
    #define CONCAT_IMPL(x,y) x##y
    #define CONCAT(x,y) CONCAT_IMPL(x,y)
    #define VAR(name) CONCAT(name,__COUNTER__)
    int main() {
    int VAR(myvar); // 展开为 int myvar0;
    int VAR(myvar); // 展开为 int myvar1;
    int VAR(myvar); // 展开为 int myvar2;
    }
  • program_invocation_name:参考man page

#pragma

#pragma weak

Synopsis

1
#pragma weak function-name1 [= function-name2]

#pragma weak means that even if the definition of the symbol is not found, no error will be reported.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

// It is not an error for symbol to never be defined at all.
// Without this line, the address of "foo" will always evaluate to "true",
// so the linker will report an "undefined reference to 'foo'" error.
#pragma weak foo
// The declaration is needed.
/* extern */ void foo();

int main() {
if (foo)
foo();

return 0;
}

Reference: 123