尝试将一个c文件链接到另一个c文件时出错

时间:2012-10-28 03:53:31

标签: c linux gcc compilation linker

我正在尝试单独编译每个c文件,然后将它们作为单个可执行文件链接在一起。以下是2个c文件:

file1.c中

#include <stdio.h>

void display();
int count;

int main() {
 printf("Inside the function main\n");
 count = 10;
 display();
}

file2.c中

#include <stdio.h>

extern int count;
void display() {
  printf("Sunday mornings are beautiful !\n");
  printf("%d\n",count);
}

但是当我尝试编译它们时,我遇到了一些错误:

当我编译file1.c

gcc file1.c -o file1
/tmp/ccV5kaGA.o: In function `main':
file1.c:(.text+0x20): undefined reference to `display'
collect2: ld returned 1 exit status

编译file2.c时

gcc file2.c -o file2
/usr/lib/gcc/i686-redhat-linux/4.6.3/../../../crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
/tmp/cczHziYd.o: In function `display':
file2.c:(.text+0x14): undefined reference to `count'
collect2: ld returned 1 exit status

我犯了什么错误?

3 个答案:

答案 0 :(得分:4)

您正在单独编译每个,但问题是您还尝试单独链接它们。

gcc file1.c file2.c  -o theprogram   # compile and link both files

或:

gcc -c file1.c        # only compiles to file1.o
gcc -c file2.c        # only compiles to file2.o

gcc file1.o file2.o -o the program   # links them together

答案 1 :(得分:2)

您必须将它们链接到单个可执行文件中。

gcc -c file1.c -o file1.o
gcc -c file2.c -o file2.o
gcc file1.o file2.o -o theprogram

答案 2 :(得分:2)

这里有两个选项:

1)在一个编译单元中编译两个c文件。这意味着每个文件都已编译,然后立即链接。

gcc file1.c file2.c -o program

这种技术的缺点是对任一文件的更改都需要从头开始完全重新编译。在一个更大的项目中,这可能是浪费时间。

2)使用.h文件声明函数并在.c文件中包含此.h文件。请务必在调用或实现其功能的每个.c文件中#include .h文件。

file1.h:

void display();

然后,使用-c标志编译每个.c文件。这可以防止gcc过早地链接代码。最后,用gcc链接两个编译的文件。

总结:

gcc -c file1.c -o file1.o
gcc -c file2.c -o file2.o
gcc file1.o file2.o -o myprogram

我建议您查看Makefiles,它可以帮助您自动执行此过程。

相关问题