Home >Backend Development >C++ >How Can I Remove Comments from C/C Source Code Using GCC?

How Can I Remove Comments from C/C Source Code Using GCC?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 12:45:12939browse

How Can I Remove Comments from C/C   Source Code Using GCC?

Removing Comments from C/C Source Code

In C/C programming, comments are essential for adding descriptive notes and documenting code. However, when you need to extract the pure source code without any comments, it can be a tedious task.

Existing Tool for Removing Comments

Rather than manually writing regexes to handle complex scenarios, there's a practical tool that can efficiently remove comments from your C/C source files. The following command utilizes the GNU Compiler Collection (GCC) to accomplish this:

gcc -fpreprocessed -dD -E -P <input_file>

Flags Explanation:

  • -fpreprocessed: Generates the preprocessed output without macros being expanded.
  • -dD: Disables macro expansion.
  • -E: Preprocesses the input without compilation.
  • -P: Outputs only the preprocessed code.

Example Usage:

Consider the following source file, test.c, containing comments and macros:

#define foo bar
foo foo foo
#ifdef foo
#undef foo
#define foo baz
#endif
foo foo
/* comments? comments. */
// c++ style comments

Running the command on test.c will produce the following output:

#define foo bar
foo foo foo
#ifdef foo
#undef foo
#define foo baz
#endif
foo foo

As you can see, all comments have been successfully stripped from the code while preserving the actual source structure.

The above is the detailed content of How Can I Remove Comments from C/C Source Code Using GCC?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn