Hacker News new | ask | show | jobs
by defap 2399 days ago
Not really too bizarre. Header files should include or declare everything they need; they should not introduce include-order dependencies. Listing your includes in lexicographic order is a good way to enforce header completeness.
2 comments

It is by convention that C/C++ headers rely on preprocessor state to determine what blocks to reveal, macros to use, et al.

It is quite common to have an auto-generated configuration header, for instance; or a precompiled header; or optional headers that, when present, mutate the behaviour of other headers.

Every time you run a configure script for a C project there's a good chance you're interacting with code in this way.

Yeah, and if you want to use clang-format include reordering in such a project, you should read the docs for clang-format's "IncludeCategories". It allows you to separate your includes into blocks by providing regexes and associated priorities. Alphabetic sorting is done only within a block.

It's not like clang-format was written by idiots who never used the language before. Maybe read up on what the tool actually does before you get all mad at them?

I'm not mad?

I think it's a harmful anti-feature that's worthy of criticism.

clang-format still allows some ordering when the SortIncludes feature is enabled. Search for IncludeBlocks in https://clang.llvm.org/docs/ClangFormatStyleOptions.html
One other ordering I've encountered which helps remove errors is to list the headers in reverse generic order. Meaning that you go from the most specific header files to the least specific. So <algorithm> and <windows.h> would be getting included last.

This helps ensure that your specific project level header files have all the necessary forward declares and includes to be a fully functioning and complete header.

I also sort my includes this way. The trouble is, determining how generic an include (inclusion?) is is a fuzzy problem. Sometimes I get stuck trying to figure out which header is more abstract, and at times I've run into side effects like this even with reverse generic sorting.
Yeah, this header sorting is only meant to be a tool to help craft header files which are independent. If that's not your project structure then you can use whatever sorting you want.

In the end though you'll have to make a decision on how to sort the projects and which one is more or less specific than another. Kind of like deciding to just sort by pointer address if all else is equal.