How to disable Eclipse CDT code formatter for a code block

Use Astyle (Artistic Style) formatter, it's far superior to the Eclipse CDT built-in formatter and has the feature you require:

http://astyle.sourceforge.net/astyle.html#_Disable_Formatting

Example:

#include <iostream>

int main(int argc, char** argv)
{
// *INDENT-OFF*
std::cout<<"hello world"<<'\n';
// *INDENT-ON*
}

Formatting this using astyle won't indent the code between // INDENT-OFF and // INDENT-ON but it will also disable any other formatting features astyle does, like the spacing of the instructions in this case.

I use it myself configured as an external tool. The only problem, external tools don't have hotkeys, but there is one hotkey to "Run Last Launched External Tool", and if you only use one external tool it works the same.

More details about the configuration (linux):

Astyle:

You can get it easily from your distribution repositories or via the official site.

To setup a configuration file with the formatting settings:

http://astyle.sourceforge.net/astyle.html#_Options_File

I use the home folder variant, just create a .astylerc in your $HOME, mine contains:

--suffix=none
--style=allman
--indent=tab=4
--max-code-length=70
--close-templates
--keep-one-line-blocks
--break-elseifs
--break-closing-brackets
--align-reference=type
--align-pointer=type
--indent-classes
--indent-modifiers
--indent-switches
--indent-cases
--indent-labels
--indent-col1-comments
--min-conditional-indent=0
--pad-oper
--pad-header
--unpad-paren

Eclipse:

"Run" menu --> External tools --> External tools Configurations... Add a new "Program" and in the configuration window:

  • Location: /usr/bin/astyle (use whereis or locate to check this)

  • Working Directory: ${project_loc}

  • Arguments: ${selected_resource_loc}

In the same window, refresh tab:

  • Tick Refresh resources upon completion.

  • Tick "The selected resource"

Same window, common tab:

  • Display in favorites menu, Tick "External tools"

Yes, you can do it since CDT supports this feature starting from version 9.7. The behavior is exactly the same of JDT.