gcc编译多个文件

gcc编译多个文件,c,gcc,C,Gcc,我有这五个来源 main.csrc_print1.csrc_print2.cheader_print1.hheader_print2.h 各文件的内容很简单,如下所示: main.c #include "header_print1.h" #include "header_print2.h" int main(int argc, char** argv) { print1(); print2(); return 0; } #include "header_print1.

我有这五个来源

main.c
src_print1.c
src_print2.c
header_print1.h
header_print2.h

各文件的内容很简单,如下所示:

main.c

#include "header_print1.h"
#include "header_print2.h"

int main(int argc, char** argv) {
    print1();
    print2();
    return 0;
}
#include "header_print1.h"

void print1() {
   printf("Hello 1\n");
}
#include "header_print2.h"

void print2() {
   printf("Hello 2\n");
}
标题_print1.h

#ifndef PRINT_1
#define PRINT_1

#include <stdio.h>
#include <stdlib.h>

void print1();

#endif
#ifndef PRINT_2
#define PRINT_2

#include <stdio.h>
#include <stdlib.h>

void print2();

#endif
src_print2.c

#include "header_print1.h"
#include "header_print2.h"

int main(int argc, char** argv) {
    print1();
    print2();
    return 0;
}
#include "header_print1.h"

void print1() {
   printf("Hello 1\n");
}
#include "header_print2.h"

void print2() {
   printf("Hello 2\n");
}
使用
gcc
我尝试使用以下命令行进行编译:

  gcc -I ./ -o test -c main.c src_print1.c src_print2.c
所有内容都在同一个文件夹中。 我得到的错误是:

gcc: cannot specify -o with -c or -S with multiple files

我查阅了gcc手册,但实际上我不知道在这种情况下该怎么办,因为我通常使用IDE而不是命令行

 gcc -I./ -o test main.c src_print1.c src_print2.c
你可以走了。当您使用
-o
指定输出二进制文件时,无需使用
-c
标志[注意]

此外,正如这里提到的,所有文件都在同一个目录中,您甚至可以将语句缩短为

 gcc -o test main.c src_print1.c src_print2.c
建议:虽然上述更改可以完成工作,但这并不是一种优雅的方式。请考虑创建一个可以让你的生活更轻松的。


[注]:

关于
-c
选项,根据(重点)

-c
编译或汇编源文件,但不要链接。链接阶段根本没有完成。最终输出为每个源文件的对象文件形式


所以,现在应该清楚了,你为什么会出错。

你应该学习如何使用
生成
与“-c”选项有什么区别?@Lukkio:这正是你在包含
-c
选项时应该问自己的问题:D它会阻止链接器运行,因此,将对象文件作为输出是没有意义的。我还认为gcc不会看到任何指定的
-I
选项(或者从其缓冲区中删除它们?),如果它们没有出现在末尾。我不知道哪个版本会这样though@pmg是的,刚刚注意到这个案子的情节。更新了。@Bastien确实有用的信息。将其作为建议纳入我的答案中。