xcode 如何将 C/C++ 函数添加到 Objective-C 代码中(iphone 相关)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6551501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add C/C++ functions to Objective-C code (iphone related)
提问by cisgreat
I added .h/.cpp files with C functions to my Xcode project. How would I call a C function in an objective-C function?
我将带有 C 函数的 .h/.cpp 文件添加到我的 Xcode 项目中。我将如何在目标 C 函数中调用 C 函数?
When I included the C file (#import "example.h") in the app delegate header file it exploded with errors (could be that it treated the cpp file as objective-c) even though it compiles fine without being included/imported.
当我在应用程序委托头文件中包含 C 文件(#import“example.h”)时,它会因错误而爆炸(可能是它将 cpp 文件视为目标 c),即使它在没有被包含/导入的情况下编译得很好。
Thanks
谢谢
Edit: Renaming all the files from m to mm fixed the issue. However I am getting a linker error when building (ld: duplicate symbol)... Better research this first. Thanks again all.
编辑:将所有文件从 m 重命名为 mm 解决了该问题。但是,我在构建时遇到链接器错误(ld:重复符号)......最好先研究一下。再次感谢大家。
回答by LaC
If you want to use C++ with your Objective-C module, change the file extension from .m
to .mm
.
如果你想用C ++与Objective-C的模块,从改变文件扩展名.m
来.mm
。
回答by Joe
To use plain C in Objective-C just include the header/source file as usual and call the functions. The C files can use the standard extension
.h
and.c
. A lot of libraries are already used this way such as libxml and sqlite.To write C code that can use Objective-C (access FoundationFramework) it will need to be placed in a
.m
file. A.m
file can contain all C functions just like the main.m generated with new projects.To call C++ code the C++ can be in a
.cpp
(or other valid extension) but your Objective-C file needs the extension.mm
to call it, and once again simply include the header file. And to use Objective-C inside of a C++ class it will need the.mm
extension.
要在 Objective-C 中使用普通 C,只需像往常一样包含头文件/源文件并调用函数。C 文件可以使用标准扩展名
.h
和.c
. 许多库已经以这种方式使用,例如 libxml 和 sqlite。要编写可以使用 Objective-C(访问 FoundationFramework)的 C 代码,需要将它放在一个
.m
文件中。一个.m
文件可以包含所有 C 函数,就像新项目生成的 main.m 一样。要调用 C++ 代码,C++ 可以位于
.cpp
(或其他有效扩展名)中,但您的 Objective-C 文件需要扩展名.mm
才能调用它,并且再次简单地包含头文件。并且要在 C++ 类中使用 Objective-C,它需要.mm
扩展。
回答by Kristopher Johnson
C functions should be callable without doing anything special. Objective-C is a superset of C.
C 函数应该是可调用的,而无需做任何特殊的事情。Objective-C 是 C 的超集。
If the headers include C++ stuff, then you need to compile your files as Objective-C++ instead of Objective-C. To do this, just change the file extensions from .m
to .mm
.
如果头文件包含 C++ 内容,那么您需要将文件编译为 Objective-C++ 而不是 Objective-C。要做到这一点,只需更改从文件扩展名.m
来.mm
。