我在 Xcode 5 中创建了一个 OSX 命令应用程序
这是主要的。
#import <Foundation/Foundation.h>
#import "ConnectionListener.h"
#import "SOMatrix.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSLog(@"Hello, World!");
print_m();
}
return 0;
}
这是我的头文件:
#ifndef __GDC1__SOMatrix__
#define __GDC1__SOMatrix__
#ifdef __cplus
#include <iostream>
#endif
int print_m();
#endif /* defined(__GDC1__SOMatrix__) */
这是 SOMatrix.mm 文件的部分列表
#include "SOMatrix.h"
#include <iostream>
using namespace std;
int print_m() {
// logic removed to keep it short; no compile time error
return 0;
}
当我构建项目时,我收到链接器错误:
Undefined symbols for architecture x86_64:
"_print_m", 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)
我不明白为什么函数被 show 更改为在名称中有一个前导下划线('_print_m')。
为什么会发生此错误?是否需要将 .mm 文件显式添加到项目中?
您需要更改以下行:
#ifdef __cplus
#include <iostream>
#endif
在您的 .h 文件中:
#ifdef __cplusplus
#include <iostream>
extern "C"
{
#endif
与同伴一起:
#ifdef __cplusplus
}
#endif
在 .h 文件的末尾。
因为你正在尝试从Objective-C访问C++函数,C++倾向于做一些名称重整(例如,添加下划线)。 添加"extern "C"
"位允许你的Objective-C代码找到你的C函数声明。这个相关问题的答案可能会比我更好地阐述事情。