2

Imagine I have file1.c, file2.c. First I compile one file with gcc -c file1.c -o file1.o. Is it OK to compile them together with gcc file1.o file2.c -o prog? I tried it and no errors are shown, but should I compile file2.o first? Is it correct to mix .c and .o files?

Vlad Havriuk
  • 1,291
  • 17
  • 29
  • What you're doing is viable for the toolchain you're using (likely clang, gcc, mingw, whatever). you'll ultimately find it is easier to xform your build instructions into actual build systems (make, cmake, etc.) if you stick to the principle of source -> target, however. – WhozCraig Jun 24 '21 at 10:20
  • @WhozCraig I use GNU make and I found out it mixes .c and .o (because I wrote it a bit wrong) with GCC compiler – Vlad Havriuk Jun 24 '21 at 10:22
  • 2
    GnuMake isn't doing that; *you* are. Make will (try to) do whatever you tell it to do. Anyway, since you're already in Make land, you may as well upsize to doing things like [automatic dependencies generation](https://stackoverflow.com/questions/8025766/makefile-auto-dependency-generation) at which point it will become pretty clear pretty quickly how moving toward target per source is a good pattern. – WhozCraig Jun 24 '21 at 10:24

1 Answers1

3

Yes, you can do gcc file1.o file2.c -o prog. You can also do gcc file1.c file2.c -o prog.

GCC will handle compiling file2.c behind the scenes.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157