1,工程以C/C++ 编译!
1,文件main.c
#include "stdio.h"
#include "M_Queue.h"
int main()
{
struct CQueue* v = NewCQueue();
M_QueuePush(v, 1);
printf("%d\n", M_QueueGetFirstIdx(v));
M_QueuePush(v, 2);
printf("%d\n", M_QueueGetFirstIdx(v));
M_QueuePush(v, 3);
printf("%d\n", M_QueueGetFirstIdx(v));
M_QueuePop(v);
printf("%d\n", M_QueueGetFirstIdx(v));
M_QueuePop(v);
printf("%d\n", M_QueueGetFirstIdx(v));
}
2,Queue.c
#ifdef __cplusplus
extern "C" {
#endif
#include "Queue.h"
bool CQueue::QueuePush(long date)
{
unsigned short tmp;
tmp = (tail + 1) & (QUEUE_ELEM_NUM - 1);
if (tmp == head)
return false;
tail = tmp;
Date[tmp] = date;
num++;
return true;
}
//------------------------------------------------------------------------------
bool CQueue::QueuePop(void)
{
if (tail == head)
return false;
head = (head + 1) & (QUEUE_ELEM_NUM - 1);
Date[head] = 0;
num--;
return true;
}
//------------------------------------------------------------------------------
unsigned short CQueue::QueueGetFirstIdx(void)
{
return ((head + 1) & (QUEUE_ELEM_NUM - 1));
}
#ifdef __cplusplus
}
#endif
3,Queue.h
#ifndef __QUEUE_H__
#define __QUEUE_H__
#ifdef __cplusplus
extern "C" {
#endif
#define QUEUE_ELEM_NUM (4) //队列元素数量
class CQueue
{
public:
bool QueuePush(long date);
bool QueuePop(void);
unsigned short QueueGetFirstIdx(void);
private:
int Date[QUEUE_ELEM_NUM] = { 0 };
unsigned short head = 0;
unsigned short tail = 0;
unsigned short num = 0;
};
#ifdef __cplusplus
}
#endif
#endif //__QUEUE_H__
4,M_Queue.cpp? -- 中间文件
#ifdef __cplusplus
extern "C" {
#endif
#include "M_Queue.h"
#include "Queue.h"
CQueue* NewCQueue()
{
return new CQueue();
}
unsigned short M_QueuePush(CQueue* v, long date)
{
return v->QueuePush(date);
}
unsigned short M_QueuePop(CQueue* v)
{
return v->QueuePop();
}
unsigned short M_QueueGetFirstIdx(CQueue* v)
{
return v->QueueGetFirstIdx();
}
#ifdef __cplusplus
}
#endif
5. M_Queue.h
#ifndef __M_QUEUE_H__
#define __M_QUEUE_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "stdio.h"
typedef struct CQueue CQueue;
CQueue* NewCQueue();
unsigned short M_QueuePush(CQueue* v, long date);
unsigned short M_QueuePop(CQueue* v);
unsigned short M_QueueGetFirstIdx(CQueue* v);
#ifdef __cplusplus
}
#endif
#endif //__M_QUEUE_H__
C文件?有什么更方便的方法调用 C++ 的包含类的函数?
麻烦之处在于写了一个中间文件。
[目前感觉,最好的方式是另开一个C++文件写出所有的逻辑应用(不带含类参数),并用extern "C {} 方式包含,然后在 C代码中调用。这样做就省去了写中间文件中的接口,直接写逻辑应用。]
2,
如果只调用C++函数,不带类定义时,直接在CPP文件中用
extern "C"{? ?
/**************************
C++函数
/**************************
}
告诉编译器以C的方式编译函数。在C文件中直接使用即可。