静态库中的extern变量,使用Objective-C

时间:2010-06-25 11:07:45

标签: c objective-c global-variables static-libraries extern

我已经构建了一个静态库,可以在我的iPhone应用程序中链接。这个库使用了一些全局变量和函数,就像在C中一样。我的问题是,当使用例如:

extern
void do_stuff (const int a)
{
    return a*a;
}

extern const int a_variable;
extern const int an_array[DEFINED_VALUE];

当我在代码中的任何地方使用此函数或访问这些变量时,编译器会告诉我

“_ do_stuff”引自: - tests.o

中的[Object testMethod]

“_ a_variable”引自: - tests.o

中的[Object testMethod]

“_ an_array”引自: - tests.o

中的[Object testMethod]

未找到符号 Collect2:Id返回1退出状态

以前有没有人遇到过这个问题?我知道我做的事情很愚蠢,我缺少一些关键的Objective-C或C概念,但我真的看不出来。所以我希望有人可以帮助我。提前谢谢。

2 个答案:

答案 0 :(得分:5)

这些是链接器错误,告诉您无法找到引用的实体。这可能意味着您尚未将库添加到项目中。

顺便说一下,你可能应该区分声明这些东西的地方,它们确实应该被声明为extern的地方,以及你定义<的地方/ em>他们,他们不应该在哪里。也就是说,您可能有一个包含以下内容的头文件:

extern void do_stuff (const int a);
extern const int a_variable;
extern const int an_array[];

然后是一个类似的实现文件:

void do_stuff (const int a)
{
    return a*a;
}

const int a_variable = 42;
const int an_array[DEFINED_VALUE] = { 1, 2, 3, 4 };

另外,在实际为a_variable时调用某些内容const有点误导!

答案 1 :(得分:0)

@walkytalky好吧,我在.a上运行nm,用grep过滤,看看这些符号是否已导出。

host-006:Release-iphonesimulator <username>$ nm -g libCardLib.a | grep CP_
nm: no name list
     U _CP_BACK
     U _CP_FILE_EXTENSION_SUFFIX
     U _CP_FILE_PATH
     U _CP_SUIT_PREFIX
     U _CP_VALUE_PREFIX
00002020 D _CP_BACK
00002018 D _CP_FILE_EXTENSION_SUFFIX
0000201c D _CP_FILE_PATH
00002024 D _CP_FRONT
00002108 D _CP_SUIT_PREFIX
0000210c D _CP_VALUE_PREFIX
nm: no name list
nm: no name list
nm: no name list

所以似乎每个符号都有一个未定义的副本?