我有一个名为
global_params.c
的文件,其中包含许多全局变量。在该文件中,我尝试将它们合并为一系列结构。我试图将它们定义为全局结构,但我一直遇到链接错误。错误是这样的:
/usr/bin/ld: tracking_main.o: warning: relocation against `calibration_options' in read-only section `.text'
/usr/bin/ld: tracking_main.o: in function `main':
tracking_main.c:(.text+0x1d2): undefined reference to `calibration_options'
/usr/bin/ld: tracking_main.c:(.text+0x1d8): undefined reference to `calibration_options'
/usr/bin/ld: tracking_main.c:(.text+0x1de): undefined reference to `calibration_options'
/usr/bin/ld: tracking_main.c:(.text+0x1e4): undefined reference to `calibration_options'
/usr/bin/ld: tracking_main.c:(.text+0x1ea): undefined reference to `calibration_options'
/usr/bin/ld: tracking_main.o:tracking_main.c:(.text+0x1f0): more undefined references to `calibration_options' follow
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status
在我的设置中,我有一个名为
global_params.c
的文件,其中包含所有全局参数并初始化结构。 calibration_options
是在文件中初始化的结构。我在我的主要函数中引用了该结构,它在tracking_main.c
中定义。我还有 2 个头文件。一个叫tracking_C.h
,我在其中声明结构,另一个叫global_params.h
,我在这里将全局变量和结构声明为extern
。我的代码非常复杂,我无法用简单的代码重现该示例。使用简单的代码它工作正常......我不能在这里提供我的所有代码来重现这个问题,但我认为提供一个简单的例子会很有用,这样你就可以理解我正在尝试做的事情:
global_params.h
extern const int param1;
extern const int param2;
extern const int param3;
extern const int param4;
extern const TestStruct1 test_struct1;
extern const TestStruct test_struct;
tracking_C.h
typedef struct TestStruct1
{
int param1;
int param2;
int param3;
int param4;
} TestStruct1;
typedef struct TestStruct
{
int param1;
int param2;
int param3;
int param4;
} TestStruct;
global_params.c
#include <stdio.h>
#include "tracking_C.h"
#include "global_params.h"
const int param1 = 1;
const int param2 = 2;
const int param3 = 3;
const int param4 = 4;
const TestStruct1 test_struct1 = {.param1=param1, .param2=param2, .param3=param3, .param4=param4};
const TestStruct test_struct = {.param1=test_struct1.param1, .param2=test_struct1.param2, .param3=test_struct1.param3, .param4=test_struct1.param4};
tracking_main.c
#include <stdio.h>
#include "tracking_C.h"
#include "global_params.h"
int main()
{
int A = test_struct.param1;
printf("Parameter 1 is: %d", A);
return 1;
}
这就是我编译代码的方式
gcc -Wall -pthread -c tracking_main.c
gcc -Wall -pthread -c global_params.c
gcc global_params.o tracking_main.o -o main
这段代码工作正常。我已经尝试过,但无法用更简单的代码重现该问题。我或多或少正在寻找有关为什么我可能会从链接器收到此错误的建议。