一、#pragma pack与#define一起使用
C代码
#ifndef PACKED
#define PACKED_BEGIN __pragma(pack(push,1))
#define PACKED
#define PACKED_END __pragma(pack(pop))
#endif
PACKED_BEGIN
struct PACKED {
short someSampleShort;
char sampleByte;
int sampleInteger;
} structType_t;
PACKED_END
C++代码,编译器支持不同
#if defined(__BORLANDC__)
#if defined(__clang__)
#define PACKED_BEGIN __pragma(pack(push, 1))
#define PACKED
#define PACKED_END __pragma(pack(pop))
#else
#error Cannot define PACKED macros for this compiler
#endif
#elif defined(_MSC_VER)
#define PACKED_BEGIN __pragma(pack(push, 1))
#define PACKED
#define PACKED_END __pragma(pack(pop))
#elif defined(__GNUC__)
#define PACKED_BEGIN
#define PACKED __attribute__((__packed__))
#define PACKED_END
#else
#error PACKED macros are not defined for this compiler
#endif
参考文章:在Borland C ++上将#pragma pack与#define一起使用
二、C++中调用C代码,出现“Undefined Reference…”
c代码的头文件已经extern但还是报错“Undefined Reference…”
解决办法:
C++中使用:
extern “C”{
[C语言头文件]
}
或C中使用:
#ifdefine _cplusplus
extern “C”{
[C语言头文件函数声明及其他变量]
}
#endif
参考文章:C++中调用C代码,出现“Undefined Reference…”
三、回调函数
typedef int (*CallbackFun)( char *p_ch );int Call (CallbackFun p_Callback, char *p_ch){ ...}回调函数:就是一个通过函数指针调用的函数,不是一个数据类型。
#include <iostream>
using namespace std;
typedef int (*CallbackFun)( char *p_ch );
int AFun (char *p_ch)
{
cout << "Afun 回调:\t" << p_ch << endl;
return 0;
}
int BFun (char *p_ch)
{
cout << "BFun 回调:\t" << p_ch << endl;
return 0;
}
int Call (CallbackFun p_Callback, char *p_ch)
{
cout << "call 直接打印出字符:\t" << p_ch << endl;
p_Callback (p_ch);
return 0;
}
int Call2 (char *p_ch, int (*pfun)(char *))
{
cout << "通过指针方式执行回调函数。。。" << endl;
( *pfun )( p_ch );
return 0;
}
int Call3 (char *p_ch, CallbackFun p_Callback)
{
cout << "通过命名方式执行回调函数。。。" << endl;
p_Callback (p_ch);
return 0;
}
int main ()
{
char *p_ch = "Hello world!";
Call (AFun, p_ch);
Call (BFun, p_ch);
Call2 (p_ch, AFun);
Call3 (p_ch, AFun);
system ("pause");
return 0;
}
参考文章:回调函数——使用typedef
四、winsock库报错
winsock库与winsock2库冲突。
在工程文件里添加
DEFINES += WIN32_LEN_AND_MEAN