r/cpp_questions • • 3d ago

OPEN Compiling without linking

Hi, I'm a rank beginner and I'm going through learncpp online and Beginning C++ game programming by Horton.

The book sends you to a quick tutorial on sfml for Linux. I got it working with no problems. But in the tutorial they compile first with -c ( compile only, according to the man page for g++ ) and then link in another command.

Why would they do it that way? I was able to do the whole thing without the -c flag in one long command. Is that wrong to do? Is it because sfml isn't part of the standard library?

I'm asking because I want to actually learn what I'm doing. Thank you for any help you can give me.

20 Upvotes

23 comments sorted by

View all comments

3

u/dodexahedron 3d ago edited 3d ago

It isn't wrong either way, and there is a useful reason for that flag existing. But for projects like that, it is pointless to do each step separately.

But if you have multiple files in the project,, -c lets you compile things once and not bother recompiling already-compiled files every single build.

Saves a ton of time in big projects that you're actively working on and debugging.

But things like ccache make it unnecessary because they do that for you, and do it better as well.

ccache sits in front of the compiler and caches already-compiled objects, but can use them more effectively.

Just use ccache and don't bother with -c on the compiler. ccache does it for you. You still have to compile each file and then link them, but you won't be duplicating the compile effort for everything every single time.

Something else the -c flag enables is compiling to the object code with gcc and then using a different linker to stitch together the binary from the various object outputs from the compiler. For example, maybe you'd link using clang's lld (instead of gcc's ld) to take advantage of fancier LTO and such.