【发布时间】:2015-03-21 08:00:41
【问题描述】:
我正在尝试编译一个程序,该程序分为 3 个模块,对应于 3 个源文件:a.c、b.c 和 z.c。 z.c 包含main() 函数,它调用a.c 和b.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.o、b.o和z.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