如果我在 c++ 环境中使用 C 代码并将所有代码包含在标头中,则一切正常。如果我尝试在头文件中声明 C 函数并在 .c 或 .cpp 文件中实现它们,则会收到以下错误:
Undefined symbols for architecture x86_64:
"vec2_norm(Vec2)", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
vec2.h
#ifndef Physics_Engine_Test_Vec2_h
#define Physics_Engine_Test_Vec2_h
typedef struct
{
float x;
float y;
} Vec2;
inline Vec2 vec2_norm(Vec2 v);
#endif
Vec2.c 或 .cpp
#include "Vec2.h"
#include <math.h>
inline Vec2 vec2_norm(Vec2 v) {
float len = v.x*v.x + v.y*v.y;
if (len) {
len = 1 / sqrtf(len);
v.x *= len;
v.y *= len;
}
return v;
}