【发布时间】:2017-08-14 23:16:53
【问题描述】:
我有两个目录,sorting 和 searching(同一目录的子目录),它们有 .c 源文件和 .h 头文件:
mbp:c $ ls sorting
array_tools.c bubble_sort.c insertion_sort.c main selection_sort.c
array_tools.h bubble_sort.h insertion_sort.h main.c selection_sort.h
mbp:c $ ls searching
array_tools.c array_tools.h binary_search.c binary_search.h linear_search.c linear_search.h main main.c
在searching 中,我正在构建一个需要使用insertion_sort 函数的可执行文件,该函数在insertion_sort.h 中声明并在insertion_sort.c 中sorting 中定义。以下编译成功生成可执行文件:
mbp:searching $ clang -Wall -pedantic -g -iquote"../sorting" -o main main.c array_tools.c binary_search.c linear_search.c ../sorting/insertion_sort.c
但是,我希望能够包含来自任意目录的函数,方法是使用 #include 包含标头,然后为编译器提供搜索路径。我需要事先将.c 文件预编译为.o 文件吗? clang 的 man 页面列出了以下选项:
-I<directory>
Add the specified directory to the search path for include files.
但是下面的编译失败了:
mbp:searching $ clang -Wall -pedantic -g -I../sorting -o main main.c array_tools.c binary_search.c linear_search.c
Undefined symbols for architecture x86_64:
"_insertion_sort", referenced from:
_main in main-1a1af0.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
main.c 有以下includes:
#include <stdio.h>
#include <stdlib.h>
#include "linear_search.h"
#include "binary_search.h"
#include "array_tools.h"
#include "insertion_sort.h"
我不明白头文件、源文件和目标文件之间的链接。要包含在.c 文件中定义的函数,考虑到.c 文件与头文件位于同一目录中,包含同名头文件是否就足够了?我已经在 SO、man 页面和许多教程上阅读了 SO 上的多个答案,但无法找到明确、明确的答案。
回应@spectras:
一个接一个,你给编译器一个源文件来处理。例如:
cc -Wall -Ipath/to/some/headers foo.c -o foo.o
跑步
mbp:sorting $ clang -Wall insertion_sort.c -o insertion_sort.o
产生以下错误:
Undefined symbols for architecture x86_64:
"_main", referenced from:
implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
【问题讨论】:
-
你有两个
main.c,想制作一个程序? -
@aschepler 我有两个
main.c,但它们位于不同的目录中。我不打算在编译中使用另一个main.c。 -
@aschepler 澄清一下,编译是从
searching目录运行的。 -
创建一个库。安装它。使用它。
-
您可以创建一个库(从长远来看通常是最简单的)或在链接命令行上列出要链接的各个目标文件。
标签: c compilation clang