'Restricting header inclusions in C++
What is the best way to restrict use of certain headers(features of the library itself) in certain Cpp files. And if it fails to follow the set rules, compilation should halt.
This is not about finding out superfluous includes. This is about restricting the developers to the applicaiton framework.
For example if there exists a osUtils class as osUtils.h and if as per this, this application's development framework mandates use of osUtils.h for filesystem operation like to make a folder. but there are always a chance that individual module finds it convenience to break this rule by including sys/stat and use a mkdir() method. But if the intention of providing a framework here lets say for cross-platform abstraction or special path handling logic, the objective is lost by doing it out of framework. Is there a way to restrict this? like restricting the usage of sys/stat.h in certain files (except for osUtils.h file in this case) can help solve the problem. but how to implement it so it will not compile if the rule is broken.
Solution 1:[1]
I don't know how to do this by breaking compilation - the idea of compilation failure because of a valid code don't appeal to me. I've got some other ideas:
- Code review. If done right this should prevent such errors.
- I am pretty sure that some static code analysis tool can help detect those things (they can check things like 'include what you use', so a rule 'don't include 'XYZ' should be there)
- If you have this static analysis tool ready there is a problem with getting people to use it and fix errors shown by it. One option that you can use is git hook. If the new code don't pass the static analysis - reject the commit. If you cannot use hooks, or don't want to - make a separate CI job that will check for the violations of the static checking. Then you'll see who and when pushed some bad code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Halny Hultaj |