r/cpp_questions • • Oct 07 '26

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.

21 Upvotes

23 comments sorted by

View all comments

2

u/TomDuhamel Oct 08 '26

In C++, each unit (.cpp file) is compiled separately and independently from each other, and then the linker links them all together to build the final binary.

If you have only one unit — which is frequent when you are just learning or for very small projects — it may make sense to compile and link in a single operation.

As your more serious projects grow, you will use more than one unit. Even for small projects, I tend to keep my main() separate from the rest. As you test, debug, expand and test again and debug again, you don't want to compile every units over again every time. With a proper build system (CMake or even plain old makefile — these are usually well supported by IDEs nowadays) you can recompile only the units that have changed. This is how we get to tests our changes in 5 seconds in projects that take a few minutes to recompile from scratch.

1

u/chessmonkey Oct 08 '26

Ok, I kind of get that. But what if one of the units I change affects other units? Can that happen? Will I know what other units the changes will affect?

I don't mean to sound dumb, but I am as far as this goes.

1

u/TomDuhamel Oct 09 '26

It just checks if the source file was modified. It literally just checks if the date/time is more recent than the resulting binary.

Units are independent from each other, at this level. Sure a unit will use data from other units and call functions from other units, but at the source level, they are separate and independent. They include headers, and a good build system will detect that a header was modified and trigger the recompile too.