C/C++语言宏定义使用实例详解
1. #ifndef 防止头文件重定义
在一个大的软件工程里面,可能会有多个文件同时包含一个头文件,当这些文件编译链接成
一个可执行文件时,就会出现大量“重定义”的错误。在头文件中实用#ifndef #define #endif能避免头文件的重定义。
方法:例如要编写头文件test.h
在头文件开头写上两行:
#ifndef TEST_H#define TEST_H //一般是文件名的大写头文件结尾写上一行:
#endif这样一个工程文件里同时包含两个test.h时,就不会出现重定义的错误了。
注:Visual C++中有一种简化的方法,那就是使用 #pragma once
2. 编写跨平台的C/C++程序
2.1 操作系统相关宏定义
Windows: WIN32 Linux: linuxSolaris: __sun2.2 编译器相关宏定义
VC: _MSC_VERGCC/G++: __GNUC__ SunCC: __SUNPRO_C 和 __SUNPRO_CC3. 完整的代码实例
//Avoid redefine anything in this header #ifndef UUID_H#define UUID_H// Check platform is Windows or Linux#ifdef _MSC_VER#ifndef DLL_API#define DLL_API __declspec(dllexport)#endif#else #ifndef DLL_API#define DLL_API #endif #endif#include <string>#include <random>#include <time.h>#include <stdlib.h>using namespace std;class DLL_API UUID {public: static string getUuidString();};#endif感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!