Objective-c ++符号没有找到陌生感 [英] Objective-c++ symbol not found strangeness

查看:95
本文介绍了Objective-c ++符号没有找到陌生感的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hej.h

  void hej(); 

hej.m

  void hej(){} 

main.mm

  #importhej.h

int main(int argc,char * argv [])
{


$ / code $ / pre
$ b $ p

hej(),引用来自:
main.o中的
符号未找到

如果我将main.mm重命名为main.m(单个m),或将hej.m重命名为mm或cpp,那么它可以工作。 (尽管没有一个解决方案是可取的,但是想象一下你想在objc ++环境中使用c-lib - 你不想改变整个lib,甚至不能,你需要在objc ++中使用它。 )



这里究竟发生了什么?

解决方案

在一个C文件( *。c,* .m )中,声明 void hej()产生一个链接器引用到名为 _hej 的C函数。当以C ++文件( *。cc,*。mm,等)编译时,该声明会生成一个链接器引用,指向C ++的损坏的名称参数的描述。 (这样做是为了支持函数重载,例如将 void hej(int) void hej(char *) )。 hej.m总是创建C名。当main.mm引用C ++名称时,它不会被找到。



为了解决这个问题,确保main.mm寻找C名,而不是C ++名。如果你控制hej.h,通常会添加如下内容,当hej.h被包含在C或C ++文件中时,它会工作:

  / * hej.h * / 
#ifdef __cplusplus
externC{
#endif

void hej();

#ifdef __cplusplus
}
#endif

如果您不拥有hej.h,您可以在main.mm中执行以下操作:

  externC{ 
#importhej.h
}

int main(int argc,char * argv [])
{
}


hej.h

void hej();

hej.m

void hej(){}

main.mm

#import "hej.h"

int main(int argc, char *argv[])
{

}

This gives me:

"hej()", referenced from: _main in main.o symbol(s) not found

If I rename main.mm to main.m (single m), or hej.m to mm or cpp, then it works. (Though none of those "solutions" are preferable. Imagine you want to use a c-lib in a objc++ environment - you wouldn't wanna change the entire lib, maybe even couldn't, and you need to use it in objc++.)

What exactly is going on here?

解决方案

When compiled in a C file (*.c, *.m), the declaration void hej() generates a linker reference to a C function named _hej. When compiled in a C++ file (*.cc, *.mm, etc.), the declaration generates a linker reference to a C++ 'mangled name', that includes in it a description of the arguments. (This is done to support function overloading, e.g. to differentiate void hej(int) from void hej(char*)). hej.m always creates the C name. When main.mm references the C++ name, it won't be found.

To resolve, ensure main.mm looks for a C name, not a C++ one. If you control hej.h, it's common to add something like the following, which would work when hej.h is included in either a C or a C++ file:

/* hej.h */
#ifdef __cplusplus
extern "C" {
#endif

void hej();

#ifdef __cplusplus
}
#endif

If you do not own hej.h, you could do the following in main.mm instead:

extern "C" {
#import "hej.h"
}

int main(int argc, char *argv[])
{
}

这篇关于Objective-c ++符号没有找到陌生感的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆