r/C_Programming • • Oct 16 '26

Question Why not specifying what to include ?

Hi, sorry if there is English mistake, it's not my first language.

I found online that the #include is replaced by preprocessor by the whole file being included, and I wondered why C isn't made so we can specify only parts of the files to include (like `import { x, y, z } from "file"` in typescript) so the compiled file is lighter ?

20 Upvotes

28 comments sorted by

View all comments

76

u/pfp-disciple Oct 16 '26

C is much older, and its design is much more straightforward. The behavior you're describing could be crudely done with macros at compile time. See #ifdef. 

Modern linkers (and probably not so modern ones) will eliminate unused code, anyway. So, if a file is included that has functions a(), b(), c,(), and d() but only b() and d() are used, the final executable won't have the code for a() and c(). 

23

u/International_Hat178 Oct 16 '26

OK, thanks to you and all other comments who explained well

17

u/vcunat Oct 16 '26

Yes, but it's good to note that the primary use of includes is to get declarations and not definitions (which live in a .c), so you normally get how to call functions but not the functions themselves. Of course there are common static inline cases, and you can "misuse" includes, etc.

5

u/pfp-disciple Oct 16 '26

I wanted to say something about that, but couldn't word it as well as you did. Thanks!

7

u/llynglas Oct 16 '26

Yes, it adds to the compile time as more text to parse, but the space and execution speed is not impacted.

1

u/flatfinger Oct 16 '26

A construct that could say "If an include file can be conveniently recognized as containing a comment bearing certain exact text at a certain offset, with the count of newline and other characters specified separately, start reading the file just past that text, and otherwise start at the beginning" would be simple to implement, and would have improved build speed on a lot of machines in the 1970s and 1980s. Likewise a construct that would invite the preprocessor to behave as though the remainder of the file contained nothing except enough #endif constructs to balance out any conditional compilation constructs.

Unfortunately, the authors of the Standard were unwilling to recognize that most compilation environments would allow efficient seeking to a given line of a file given the number of non-newline characters preceding it. Some would do this by skipping the first (line #)+(other bytes) bytes of the file, some by skipping the first (line #)*2+other bytes) bytes, and some record-based file systems would do it by skipping to the specified record. The authors of the Standard, however, didn't want to be seen as discriminating against file systems that couldn't usefully seek to a text file location via any of those means.