How to delete dead code or code of no use based on configure file/makefile file

1267 views c++

When we compile a C/C++ project, some files and codes in the project source are not needed for compilation. For example, test folder (some testing scripts), examples folder and dead code. How can I recognize these source files that are not compiled to binary files? It is not hoped that compiling is necessary. Cause I need to process many projects automatically and it is really hard to compile all projects without manual operations.

answered question

Since you've tagged cmake there a simple solution: Multiple targets. One target for the main executable program, and another target for the program to run the tests. The main executable target will of course not have any test sources included.

Explain: why you need to delete dead code? It might be impossible in general ! What happens to you if some dead code remains? So please edit your question. You should add several more paragraphs in it (with motivation and context) and show some Minimal, Complete, and Verifiable example

1 Answer


Dead code would often -but not always- be eliminated by the compiler, when you ask it to optimize (but removing all dead code automatically is impossible, since undecidable because of equivalence with the halting problem). Be aware of the as-if rule permitting the compiler to do such optimizations. So in practice you don't need to remove the corresponding source code.

Some industries have as a coding rule (e.g. in DO-178C) the requirement that dead source code is forbidden. Detecting that is extremely difficult and in general impossible (see e.g. Rice's theorem), so requires a lot of sophisticated static program analysis techniques and external code review and costs a big lot (e.g. increase the cost of software development by more than 30x).

Your build automation system (e.g. cmake or Makefile, etc...) might be (and usually is) Turing-complete; so even removing entirely useless C++ source files is an impossible task in general. Even the POSIX shell (used in commands to build your thing) is difficult to analyze (see the excellent Parsing Posix [S]hell talk by Yann Regis-Gianas at FOSDEM2018).

posted this

Have an answer?


Please login first before posting an answer.