我见过许多程序,包括如下所示的结构
typedef struct
{
int i;
char k;
} elem;
elem user;
Run Code Online (Sandbox Code Playgroud)
为什么经常这么需要?任何具体原因或适用范围?
我很难理解为什么以下代码(带有标准布局的UDT)在visual C++ 2012中给出了C-linkage警告:
warning C4190: 'vec3_add' has C-linkage specified, but returns UDT 'vec3' which is incompatible with C
typedef struct vec3 {
float x;
float y;
float z;
#ifdef __cplusplus
vec3(float x, float y, float z) : x(x), y(y), z(z) {}
#endif
} vec3;
#ifdef __cplusplus
extern "C" {
#endif
vec3 vec3_add(vec3 a, vec3 b);
#ifdef __cplusplus
}
Run Code Online (Sandbox Code Playgroud)
函数的定义在C++文件中:
vec3
vec3_add(vec3 a, vec3 b) {
static_assert(std::is_standard_layout<vec3>::value == true, "incompatible vec3 type");
return vec3(a.x + b.x, a.y + b.y, a.z + …Run Code Online (Sandbox Code Playgroud) [这个问题有一个重复的问题,我可以找到,但这个答案是完全错误的,请参阅下面的 C 代码。]
据我了解,extern "C"C++ 中不会生成 C 代码。它只是一个链接指令。
我有一些这样的extern "C"故事要讲,但今天有一个让我困扰的故事。这是一个完全最新的VS2019,代码如下:
#include <stdint.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
// NOTE: in here it is still C++ code,
// extern "C" is a linkage directive
typedef struct Test Test;
struct Test {
/* remove this const and MSVC makes no warning
leave it in and MSVC complains, a lot
GCC or clang could not care less
*/
const
uint32_t x;
} ;
/* …Run Code Online (Sandbox Code Playgroud)