【问题标题】:Calling C++ method from Objective C从 Objective C 调用 C++ 方法
【发布时间】:2011-05-26 06:27:07
【问题描述】:

我有以下文件。

foo.h(C++ 头文件)
foo.mm(C++ 文件)
test_viewcontroller.h(目标 c 头文件)
test_viewcontroller.m(目标c文件)

我在 foo.h 中声明了一个方法 donthing() 并在 foo.mm 中定义了它。假设它是

双无(双a) { 返回一个; }

现在,我尝试在 test_viewcontroller.m 中调用这个函数

double var = donthing(somevar);

我在 test_viewcontroller.o
collect2: ld 返回 1 退出状态中显示“找不到符号”_donothing() 的链接器错误

谁能指点我哪里出了问题?


让我准确地说:

#ifdef __cplusplus 

extern "C" 
{
      char UTMLetterDesignator(double Lat);
      NSString * LLtoUTM(double Lat,double Long,double UTMNorthing, double UTMEasting);
      double test(double a);
}

#endif

@卡尔

我已经包含了我的代码示例。是说我只需要在 ifdef 中包装 test() 方法。我不明白它有什么不同。你能解释一下吗?

【问题讨论】:

    标签: iphone objective-c linker-errors


    【解决方案1】:

    test_viewcontroller.m 正在为donothing() 寻找一个非 C++ 损坏的符号名称。将其扩展名更改为.mm,您应该会很好。或者,在编译 C++ 文件时,在 foo.h 中的方法声明中添加 extern "C" 声明。

    你想让它看起来像这样:

    foo.h:

    #ifdef __cplusplus
    extern "C" {
    #endif
    
    double donothing(double a);
    
    #ifdef __cplusplus
    }
    #endif
    

    foo.mm:

    #include "foo.h"
    
    double donothing(double a)
    {
        return a;
    }
    

    test_viewcontroller.m:

    #import "foo.h"
    
    - (double)myObjectiveCMethod:(double)x
    {
        return donothing(x);
    }
    

    【讨论】:

    • 我尝试添加 extern "c"。但我得到一个新错误 - “预期标识符或 '(' 在字符串常量之前”
    • @whocares,您只需要为 C++ 添加 extern "C" - 这意味着将其包装在 #ifdef __cplusplus 块中。
    • @Carl - 非常感谢您的回复!链接器错误现在消失了!!但是我在“test_viewcontroller.m”中收到了一个新警告-函数“donothing()”的隐式声明。我相信只有当我没有包含具有函数声明的头文件时才会发生这种情况。但是我有一个导入的 foo.h在“test_viewcontroller.m”中。你能告诉我有什么问题吗?
    • @whocares,我猜这意味着您的 #ifdef 块太大了。 只是extern "C" 放在#ifdef 中,而不是整个函数声明。
    • @whocares:现在你需要接受答案,因为它解决了你的问题。
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 2014-03-22
    相关资源
    最近更新 更多