gcc 链接器如何工作以包含文件
这确实是一个新手问题。我正在学习C,但我不明白如何链接在一起 不同的文件。
我有一个类似
/* file2.h */
int increment(int x);
C 文件的
/* file2.c */
#include "file2.h"
int increment(int x)
{
return x+1;
}
标头,现在我想将标头包含在 file1.c
中,以便使用函数 increment
。 根据我的理解,我必须做类似的事情:
/* file1.c*/
#include "file2.h"
int main()
{
int y = increment(1);
return 0;
}
但是当我尝试编译整个东西时,使用
gcc -o program file1.c
我收到一条错误消息,例如
/tmp/ccDdiWyO.o: In function `main':
file1.c:(.text+0xe): undefined reference to `increment'
collect2: ld returned 1 exit status
但是如果我还包含 file2.c
/* file1.c*/
#include "file2.h"
#include "file2.c" /* <--- here it is! */
int main()
{
int y = increment(1);
return 0;
}
一切都会按预期工作。
但是,如果我理解只需要包含头文件(其中仅包含声明)。那么我如何通知gcc
在file2.h
中声明的函数increment
的定义在file2.c
中?
This is really a newbie question. I'm learning C, and I don't understand how to link together
different files.
I have a header like
/* file2.h */
int increment(int x);
and a C file
/* file2.c */
#include "file2.h"
int increment(int x)
{
return x+1;
}
Now I want to include the header in file1.c
in order to use the function increment
.
From what I have understood I have to do something like:
/* file1.c*/
#include "file2.h"
int main()
{
int y = increment(1);
return 0;
}
But when I try to compile the whole thing, using
gcc -o program file1.c
I get an error message like
/tmp/ccDdiWyO.o: In function `main':
file1.c:(.text+0xe): undefined reference to `increment'
collect2: ld returned 1 exit status
However if I include also file2.c
/* file1.c*/
#include "file2.h"
#include "file2.c" /* <--- here it is! */
int main()
{
int y = increment(1);
return 0;
}
Everything works as expected.
But if I have understood only the header file (with only declarations in it) has to be included. So how can I inform gcc
that the definition of function increment
declared in file2.h
is in file2.c
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是直接编译它们:
但对于更复杂的系统,您可能需要分步骤进行。这是一个简单的命令行配方:
对于像这样复杂的事情,更好的方法是使用 make,不过。
除了您的具体问题之外,您为什么使用 GCC?您可以使用 clang 并获得更好的错误消息、更快的编译速度,并感觉自己生活在未来!
The easiest way is to compile them both directly:
But for more complicated systems you might want to do it in steps. Here's a simple command line recipe:
Even better for something complicated like this would be to use make, though.
Aside from your specific problem, why are you using GCC? You could use clang and get better error messages, faster compiling, and feel like you're living in the future!
gcc -o program file2.c file1.c
这将编译 file1.c 和 file2.c 并将它们链接在一起。
gcc -o program file2.c file1.c
this will compile file1.c and file2.c and link them together.