C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ 预定义宏

查看C++ 预定义宏的方法

作者:java叶新东

本文主要介绍了查看C++ 预定义宏的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

什么是预宏定义

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

预定义宏特征

预定义宏有两个特征:

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

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

    std::cout <<"当前行号:"<<__LINE__ << std::endl; // 当前行号:15
	
    std::cout <<"当前文件:"<<__FILE__ << std::endl; // 当前文件:/Users/yexd/Documents/project_cpp/cpp_learn/lesson_26__LINE__.cpp

    std::cout <<"当前日期:"<<__DATE__ << std::endl; // 当前日期:Apr 16 2023

    std::cout <<"当前时间:"<<__TIME__ << std::endl; // 当前时间:10:18:11
	
    std::cout <<"当前函数:"<<__FUNCTION__ << std::endl; // 当前函数:main
	
    //__STDC__:判断当前的编译器是否为标准C编译器,若是则返回值1
    std::cout <<"当前编译器:"<<__STDC__ << std::endl; // 当前编译器:1

常见操作系统预定义宏

OSMacroDescription
UNIX Environment __unix__
UNIX Environment__unix
Linux kernellinux
GNU/Linuxgnu_linux
Mac OS X & iOSAPPLE苹果系统
AndroidANDROID安卓系统
Windows_WIN32Defined for both 32-bit and 64-bit environments
Windows_WIN64Defined for 64-bit environments

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

gcc -dM -E - < /dev/null
或
cpp -dM /dev/null

指令说明

结果如下

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

clang 查看所有预定义宏

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

结果如下

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

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

gcc -dM -E helloworld.c

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

#include "iostream"
using namespace std;

#if defined(_MSC_VER) // 如果是windows系统,引入direct.h,将 _getcwd 宏定义为 GetCurrentDir
    #include <direct.h>
    #define GetCurrentDir _getcwd
#elif defined(__unix__) || defined(__APPLE__) // 如果是unix系统或者苹果系统,引入unistd.h ,将 getcwd 宏定义为 GetCurrentDir
    #include <unistd.h>
    #define GetCurrentDir getcwd
#else
// 啥也不干
#endif

// 操作系统兼容,在不同的操作系统中获取当前文件目录的方法
std::string get_current_directory()
{
    char buff[250];
    // 如果是windows系统,就用 _getcwd,如果是mac系统就用 getcwd
    GetCurrentDir(buff, 250);
    string current_working_directory(buff);
    return current_working_directory;
}

int main(int argc, char* argv[])
{
    std::cout << "当前工作目录为: " << get_current_directory() << endl;
    return 0;
}

到此这篇关于查看C++ 预定义宏的方法的文章就介绍到这了,更多相关C++ 预定义宏内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文