【发布时间】:2015-03-07 03:52:26
【问题描述】:
我有一个巨大的 C++ 程序,它使用 -O3 优化编译得很好,但在使用 -g 选项编译时会出现“未定义的对 strings_array_multilevel 变量的引用”错误(删除了 -O3)。
我已经稍微减少了测试用例。如果您遇到类似的错误,请告诉我您是如何解决的。我有一个名为 libtest.so 的库。文件 test.c 使用标准 gcc 命令编译到库中。需要注意的是,头文件 test.h 有一个数组声明为 extern (strings_array_multilevel)
const struct mystruct elem3 = {
{30, 9, 26},
{
{
{9, 9},
{9, 9}
},
{
{9, 11},
{9, 11}
}
},
(char**)strings_array_multilevel
};
test.h : 请看这里http://pastebin.com/rPULDeXk
include <stdio.h>
const int NUM_AIRORTS = 10;
const int NUM_REGIONS = 1024;
struct mystruct {
int field1[3];
int field2[2][2][2];
char ** strings;
};
extern const char* strings_array_multilevel[NUM_AIRORTS][NUM_REGIONS];
const struct mystruct elem0 = {
{0,0,0},
{
{
{0,0},
{0,0}
},
{
{0,0},
{0,0}
}
},
0
};
const struct mystruct elem1 = {
{30, 9, 26},
{
{
{9, 9},
{9, 9}
},
{
{9, 11},
{9, 11}
}
},
NULL
};
const struct mystruct elem2 = {
{0,0,0},
{
{
{0,0},
{0,0}
},
{
{0,0},
{0,0}
}
},
NULL
};
const struct mystruct elem3 = {
{30, 9, 26},
{
{
{9, 9},
{9, 9}
},
{
{9, 11},
{9, 11}
}
},
(char**)strings_array_multilevel
};
int doStuff (int index1, int latency);
test.c : 请看这里http://pastebin.com/GnSZAZUx
#include <stdio.h>
#include "test.h"
const struct mystruct* mystructarray[4] = {&elem0, &elem1, &elem2, &elem3};
int doStuff (int index1, int index) {
int retVal = 0;
retVal = mystructarray[index1]->field1[index];
return retVal;
}
const char* strings_array_multilevel[NUM_AIRORTS][NUM_REGIONS] =
{
{
"SJC", "SFO", "OAK"
},
{
"NYC", "WP", "LGA", "PHY"
}
};
Makefile :请看这里http://pastebin.com/y4LMg2SR
all:
g++ -fpic -c test.c -o test.o
g++ -shared -o libtest.so test.o
clean:
rm test.o libtest.so
现在,当我在我的项目中包含 test.h 并使用选项 -g 将其与 libtest.so 链接时,出现以下错误
cat use_library.c
#include <stdio.h>
int main () {
printf ("hello world\n");
return 0;
}
以下作品。
g++ -O3 use_library.c -L<original_directory> -ltest
以下失败
g++ -g use_library.c -L<original_directory> -ltest
Undefined reference to strings_array_multilevel
如果你能解决这个问题,请告诉我。抱歉,由于代码的私密性,我不能在这里分享。
谢谢
【问题讨论】:
-
同时使用
-g和-O3进行编译会发生什么? -
是的 "==" 是一个错字。现在更正了。
-
@ChristopherCreutzig,当我同时使用两者时,错误不存在。我使用“nm”命令/实用程序并验证 strings_array_multilevel 在导出的库中定义。
-
-g和-O是不同的选项(-g被转换为-g2)。-g是调试信息,-O是优化信息。它们没有纠缠在一起,您可以使用-O0 -g3或-O3 and -g2构建。一个不影响另一个。如果您想获得最大的调试信息,请使用-g3。-g3包括符号定义。 -
为什么用g++和gcc编译?这将导致这些名称的差异。