【问题标题】:Undefined reference to global variable during linking链接期间对全局变量的未定义引用
【发布时间】:2015-03-21 08:00:41
【问题描述】:

我正在尝试编译一个程序,该程序分为 3 个模块,对应于 3 个源文件:a.cb.cz.cz.c 包含main() 函数,它调用a.cb.c 中的函数。此外,a.c 中的函数调用b.c 中的函数,反之亦然。最后,还有一个全局变量count,这三个模块都使用了这个变量,定义在一个单独的头文件global.h中。

源文件代码如下:

a.c

#include "global.h"
#include "b.h"
#include "a.h"

int functAb() {
    functB();
    functA();
    return 0;
}

int functA() {
    count++;
    printf("A:%d\n", count);
    return 0;
}

b.c

#include "global.h"
#include "a.h"
#include "b.h"

int functBa() {
    functA();
    functB();
    return 0;
}

int functB() {
    count++;
    printf("B:%d\n", count);
    return 0;
}

z.c

#include "a.h"
#include "b.h"
#include "global.h"

int main() {
    count = 0;
    functAb();
    functBa();
    return 0;
}

头文件:

a.h

#ifndef A_H
#define A_H

#include <stdio.h>

int functA();
int functAb();

#endif

b.h

#ifndef B_H
#define B_H

#include <stdio.h>

int functB();
int functBa();

#endif

global.h

#ifndef GLOBAL_H
#define GLOBAL_H

extern int count;

#endif

最后,makefile 重现了我的错误:

CC = gcc
CFLAGS = -O3 -march=native -Wall -Wno-unused-result

z:  a.o b.o z.o global.h
    $(CC) -o z a.o b.o z.o $(CFLAGS)
a.o:    a.c b.h global.h
    $(CC) -c a.c $(CFLAGS)
b.o:    b.c a.h global.h
    $(CC) -c b.c $(CFLAGS)
z.o:    z.c a.h global.h
    $(CC) -c z.c $(CFLAGS)

有了这个,我可以编译对象a.ob.oz.o,但是,当与make z链接时,我得到了undefined reference to 'count'

z.o: In function `main':
z.c:(.text.startup+0x8): undefined reference to `count'
a.o: In function `functAb':
a.c:(.text+0xd): undefined reference to `count'
a.c:(.text+0x22): undefined reference to `count'
a.o: In function `functA':
a.c:(.text+0x46): undefined reference to `count'
a.c:(.text+0x5b): undefined reference to `count'
b.o:b.c:(.text+0xd): more undefined references to `count' follow
collect2: ld returned 1 exit status

我设法在这个最小示例中重现了我的实际代码中的错误,所以我猜模块之间的依赖关系存在问题,但我无法发现它。谁能指出我正确的方向?

【问题讨论】:

    标签: c gcc compilation linker


    【解决方案1】:

    将您的 z.c 更改为

    #include "a.h"
    #include "b.h"
    #include "global.h"
    
    int count; /* Definition here */
    int main() {
        count = 0;
        functAb();
        functBa();
        return 0;
    }
    

    global.h 开始,您的所有文件都继承了变量count声明,但所有文件中都缺少定义

    您必须将定义添加到int count = some_value; 的文件之一

    【讨论】:

    • “int count”可以在main函数里面吗?
    • @Taozi 不,它会使count 成为局部变量。我们需要一个全局定义。
    【解决方案2】:

    你有声明计数,而不是定义它。

    extern 是声明的一部分,而不是定义。

    明确地说,extern 是存储类说明符,在声明时使用。

    您需要在源文件的某处定义 int count

    【讨论】:

      【解决方案3】:

      您必须将 int count; 添加到您的 z.c 文件中。 这是因为在头文件中将变量声明为extern 会告诉编译器该变量将在另一个文件中声明,但该变量尚未声明,将由链接器解析。

      然后你需要在某处声明变量。

      【讨论】:

      • 是的,这太邪恶了。对不起所有的初学者:)
      猜你喜欢
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      相关资源
      最近更新 更多