#define和typedef在windows上的应用

时间:2023-03-08 17:44:29
#define和typedef在windows上的应用

typedef的应用

typedef是在计算机编程语言中用来为复杂的声明定义简单的别名。

下面的代码定义了一些常见类型的别名

typedef int                 INT;
typedef unsigned int UINT;
typedef unsigned int *PUINT;

windows通常定义结构体的同时会定义结构体的别名,下面的代码定义了tagPAINTSTRUCT结构体,同时给了定义PAINTSTRUCT别名以及指针类型的别名PPAINTSTRUCT等。

typedef struct tagPAINTSTRUCT {
HDC hdc;
BOOL fErase;
RECT rcPaint;
BOOL fRestore;
BOOL fIncUpdate;
BYTE rgbReserved[32];
} PAINTSTRUCT, *PPAINTSTRUCT, *NPPAINTSTRUCT, *LPPAINTSTRUCT;

#define的应用

1. 简单的define定义

#define MAX_PATH          260

2. define定义函数

 #define max(a,b)            (((a) > (b)) ? (a) : (b))

3. #和##操作符

 ##用于连接字符,windows的应用之一就是TEXT定义。

TEXT("Hello")等价于__TEXT("Hello"),__TEXT("Hello")等价于L"Hello"。

#define TEXT(quote) __TEXT(quote)
#define __TEXT(quote) L##quote

  #用于给字符加双引号,MKSTR(HELLO C++)等价于"HELLO C++"

#define MKSTR( x ) #x

4.多行定义

"afxmsg.h"下ON_WM_PAINT()宏定义如下。

 #define  ON_WM_PAINT() \
{ WM_PAINT,  0 ,  0 ,  0 , AfxSig_vv, \
(AFX_PMSG)(AFX_PMSGW) \
(static_cast <   void  (AFX_MSG_CALL CWnd:: * )( void )  >  (  & ThisClass :: OnPaint)) } ,

5.条件编译

CreateWindow在Unicode和MBCS下执行不同的函数。

#ifdef UNICODE
#define CreateWindow CreateWindowW
#else
#define CreateWindow CreateWindowA
#endif // !UNICODE

6.预编译宏定义

c++提供了一些预编译宏定义,__LINE__,__FILE__,__DATE__,__TIME__。

#include <iostream>
using namespace std;
int main () {
cout << "Value of __LINE__ : " << __LINE__ << endl;
cout << "Value of __FILE__ : " << __FILE__ << endl;
cout << "Value of __DATE__ : " << __DATE__ << endl;
cout << "Value of __TIME__ : " << __TIME__ << endl;
return 0;
}

编译输出结果如下

Value of __LINE__ : 5
Value of __FILE__ : main.cpp
Value of __DATE__ : Oct 21 2016
Value of __TIME__ : 01:01:48