Kai*_*aan 4 c c++ dll visual-studio-2010
我有一个简单的问题.我有两个库,一个用C编译,另一个用C++编译,其中C库由C++库链接和加载.我需要在C库中声明一个可以读写的结构实例.你是如何做到这一点的?
谢谢
编辑:补充说它是一个结构的实例,而不仅仅是声明
您需要创建单个头文件,该文件包含在C和C++库中的模块中:
#ifndef YOURSTRUCT_H
#define YOURSTRUCT_H
#ifdef __cplusplus
extern "C" {
#endif
struct YourStruct
{
// your contents here
};
#ifdef __cplusplus
}
#endif
// UPDATE: declare an instance here:
extern YourStruct yourInstance;
#endif
Run Code Online (Sandbox Code Playgroud)
这种形式的头文件意味着两个编译器都会很乐意读取头文件,并且两者都会生成相同的名称.
更新:
然后你需要一个模块文件.只是一个.要么是C文件要包含在C库中,要么是C++文件(如果它要包含在c ++库中):
#include "yourstruct.h"
YourStruct yourInstance;
Run Code Online (Sandbox Code Playgroud)
现在,全局实例的任何客户端,无论是C客户端还是C++客户端,都必须#include "yourstruct.h"
参考yourInstance
更新:
正如Matthieu指出的那样,最好将指针传递给周围的实例.例如.
#include "yourstruct.h"
#ifdef __cplusplus
extern "C" {
#endif
void yourFunction(YourStruct* someInstance);
#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)