Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc compile multiple files

Tags:

c

gcc

I have these five source

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

the contents are simple and are as following for respective files:

main.c

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

int main(int argc, char** argv) {
    print1();
    print2();
    return 0;
}

header_print1.h

#ifndef PRINT_1
#define PRINT_1

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

void print1();

#endif

header_print2.h

#ifndef PRINT_2
#define PRINT_2

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

void print2();

#endif

src_print1.c

#include "header_print1.h"

void print1() {
   printf("Hello 1\n");
}

src_print2.c

#include "header_print2.h"

void print2() {
   printf("Hello 2\n");
}

Using gcc I have tried to compile using the following command line:

  gcc -I ./ -o test -c main.c src_print1.c src_print2.c

Everything is in the same folder. The error I get is:

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

I looked up at gcc manual, but actually I don't understand what to do in this case, since usually I use IDE and not the command line.

like image 734
user8469759 Avatar asked Dec 14 '22 13:12

user8469759


1 Answers

IMHO, if you rewrite your compilation statement like

 gcc -I./ -o test main.c src_print1.c src_print2.c

You'll be good to go. There is no need for -c flag [NOTE] when you're specifying the output binary using -o.

Also, as mentioned here, all the files are in same directory, you can even shorten the statement as

 gcc -o test main.c src_print1.c src_print2.c

Suggestion: While the above change(s) will do the job, this is not considered an elegant way of doing so. Please consider creating a makefile which will make your life easier.


[Note]:

Regarding the -c option, as per the online gcc manual, (emphasis mine)

-c
Compile or assemble the source files, but do not link. The linking stage simply is not done. The ultimate output is in the form of an object file for each source file.

So, it should be clear by now, why you got the error.

like image 71
Sourav Ghosh Avatar answered Dec 29 '22 04:12

Sourav Ghosh