查看C++ 预定义宏

发布时间:2023-04-16 10:12:15 作者:yexindonglai@163.com 阅读(999)

什么是预宏定义

预定义宏是C语言中标准编译器预先定义的宏,当我们编写跨平台程序时,有时候需要知道对应平台的工具链GCC预定义宏,用来判断一些平台特性

预定义宏特征

预定义宏有两个特征:

  1. 无需提供它们的定义,就可以直接使用。
  2. 预定义宏没有参数,且不可被重定义。

预定义的宏一般分为两类:标准预定义宏、编译器预定义宏。
常用的几个标准预定义宏有以下几个:

  1. std::cout <<"当前行号:"<<__LINE__ << std::endl; // 当前行号:15
  2. std::cout <<"当前文件:"<<__FILE__ << std::endl; // 当前文件:/Users/yexd/Documents/project_cpp/cpp_learn/lesson_26__LINE__.cpp
  3. std::cout <<"当前日期:"<<__DATE__ << std::endl; // 当前日期:Apr 16 2023
  4. std::cout <<"当前时间:"<<__TIME__ << std::endl; // 当前时间:10:18:11
  5. std::cout <<"当前函数:"<<__FUNCTION__ << std::endl; // 当前函数:main
  6. //__STDC__:判断当前的编译器是否为标准C编译器,若是则返回值1
  7. std::cout <<"当前编译器:"<<__STDC__ << std::endl; // 当前编译器:1

常见操作系统预定义宏

OS Macro Description
UNIX Environment __ unix__
UNIX Environment __unix
Linux kernel linux
GNU/Linux gnu_linux
Mac OS X & iOS APPLE 苹果系统
Android ANDROID 安卓系统
Windows _WIN32 Defined for both 32-bit and 64-bit environments
Windows _WIN64 Defined for 64-bit environments

gcc 查看gcc默认的内置宏定义

  1. gcc -dM -E - < /dev/null
  2. cpp -dM /dev/null

指令说明

  • -E 预处理后即停止,不进行编译。预处理后的代码送往标准输出。GCC忽略任何不需要预处理的输入文件。
  • -dM 告诉预处理器输出有效的宏定义列表(预处理结束时仍然有效的宏定义)。该选项需结合`-E’选项使用。

结果如下

  1. yexd@yexddeMacBook-Pro lesson_27_namespace % gcc -dM -E - < /dev/null
  2. #define _LP64 1
  3. #define __APPLE_CC__ 6000
  4. #define __APPLE__ 1
  5. #define __ATOMIC_ACQUIRE 2
  6. #define __ATOMIC_ACQ_REL 4
  7. #define __ATOMIC_CONSUME 1
  8. ......

clang 查看所有预定义宏

  1. clang -dM -E -x c /dev/null

结果如下

  1. yexd@yexddeMacBook-Pro lesson_27_namespace % clang -dM -E -x c /dev/null
  2. #define _LP64 1
  3. #define __APPLE_CC__ 6000
  4. #define __APPLE__ 1
  5. #define __ATOMIC_ACQUIRE 2
  6. #define __ATOMIC_ACQ_REL 4
  7. #define __ATOMIC_CONSUME 1
  8. ......

查看用户自行设定的宏定义

  1. gcc -dM -E helloworld.c

预宏定义在c++代码中的应用

  1. #include "iostream"
  2. using namespace std;
  3. #if defined(_MSC_VER) // 如果是windows系统,引入direct.h,将 _getcwd 宏定义为 GetCurrentDir
  4. #include <direct.h>
  5. #define GetCurrentDir _getcwd
  6. #elif defined(__unix__) || defined(__APPLE__) // 如果是unix系统或者苹果系统,引入unistd.h ,将 getcwd 宏定义为 GetCurrentDir
  7. #include <unistd.h>
  8. #define GetCurrentDir getcwd
  9. #else
  10. // 啥也不干
  11. #endif
  12. // 操作系统兼容,在不同的操作系统中获取当前文件目录的方法
  13. std::string get_current_directory()
  14. {
  15. char buff[250];
  16. // 如果是windows系统,就用 _getcwd,如果是mac系统就用 getcwd
  17. GetCurrentDir(buff, 250);
  18. string current_working_directory(buff);
  19. return current_working_directory;
  20. }
  21. int main(int argc, char* argv[])
  22. {
  23. std::cout << "当前工作目录为: " << get_current_directory() << endl;
  24. return 0;
  25. }

关键字c++