GCC链接库进行编译 [英] GCC linked library for compile
问题描述
当源文件中已经以 #include 的形式包含信息时,为什么我们要告诉 gcc 要链接到哪个库?
Why do we have to tell gcc which library to link against when that information is already in source file in form of #include?
例如,如果我有一个使用线程并具有以下代码的代码:
For example, if I have a code which uses threads and has:
#include <pthread.h>
我仍然必须使用 gcc 中的 -pthread 选项进行编译:
I still have to compile it with -pthread option in gcc:
gcc -pthread test.c
如果我不提供 -pthread 选项,则会在查找线程函数定义时出现错误.
If I don't give -pthread option it will give errors finding thread function definitions.
我正在使用此版本:
gcc --version
gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
推荐答案
这可能是使初学者接触C的最常见事物之一.
This may be one of the most common things that trip up beginners to C.
在C语言中,有两个不同的步骤来构建程序,即编译和链接.就您的问题而言,这些步骤将您的代码连接到两种不同类型的文件(标头和库).
In C there are two different steps to building a program, compilation and linking. For the purposes of your question, these steps connect your code to two different types of files, headers and libraries.
C代码中的 #include< pthread.h>
指令由编译器处理.编译器(实际上是预处理器)在将C文件转换为目标文件之前,实际上将 pthread.h
的内容粘贴到您的代码中.
The #include <pthread.h>
directive in your C code is handled by the compiler. The compiler (actually preprocessor) literally pastes in the contents of pthread.h
into your code before turning your C file into an object file.
pthread.h
是头文件,而不是库.它包含可以在库中找到的函数,它们采用哪些自变量以及返回什么的列表.标头可以不带库而存在,反之亦然.标头是一个文本文件,通常在Unix衍生的系统上的/usr/include
中找到.您可以像打开任何C文件一样打开它以读取内容.
pthread.h
is a header file, not a library. It contains a list of the functions that you can expect to find in the library, what arguments they take and what they return. A header can exist without a library and vice-versa. The header is a text file, often found in /usr/include
on Unix-derived systems. You can open it just like any C file to read the contents.
命令行 gcc -lpthread test.c
进行编译和链接.在过去,您首先要做的是 cc test.c
,然后是 ld -lpthread test.o
.如您所见, -lpthread
实际上是链接器的一个选项.
The command line gcc -lpthread test.c
does both compilation and linking. In the old days, you would first do something like cc test.c
, then ld -lpthread test.o
. As you can see, -lpthread
is actually an option to the linker.
链接器对诸如C代码或标头之类的文本文件一无所知.它仅适用于编译的目标文件和现有库. -l </code>标志告诉它要查找哪些库以查找您正在使用的功能.
The linker does not know anything about text files like C code or headers. It only works with compiled object files and existing libraries. The -l
flag tells it which libraries to look in to find the functions you are using.
这篇关于GCC链接库进行编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!