Hey there, fellow coder! Want to hear a joke before we get started with this C++ dev tools setup tutorial ?

If you have not done it yet, you can read our article on how to setup your C++ dev environment we used.

Why did the programmer quit his job? Because he didn’t get arrays! 😂

You can read our article on how to use Git Workflow for project collaboration for better code quality.


Let’s get serious, whenever you want to build c++ applications, you need to prepare a good setup.

In this C++ dev tools setup tutorial, I will show you how I used to setup my C++ environment before starting to write any line of code.

But don’t worry, we’re here to make sure you’re all set up with the right tools to write some awesome C++ code. So let’s get started and get you ready to write some killer C++ programs!


CLion is a popular integrated development environment (IDE) for C and C++ programming. CLion is developed by https://www.jetbrains.com/ and is known for its powerful features and intelligent code assistance.

Getting Started with CLion:

Step 1: Installation

  1. Download and Install CLion:
    • Windows users can download from this link.
    • Follow the installation instructions provided for your operating system.
  2. License Activation:
    • Open CLion and activate your license if you have one. You can use it for free during the trial period.

Step 2: Creating a New Project

  1. Open CLion:
    • Once installed, open CLion.
  2. Create a New Project:
    • Choose “Create New Project.”
    • Select the project type (C or C++), and choose the appropriate toolchain.
    • Choose a C++ language standard, such as C++17.
  3. Configure Project Settings:
    • Configure project settings like project name, location, and compiler options.
  4. Finish:
    • Click “Finish” to create your project.

Step 3: Exploring the IDE

  1. Project Explorer:
    • On the left side, you have the project explorer. This shows your project structure.
  2. Code Editor:
    • The main area is the code editor. Write your code here.
  3. Toolbar:
    • The toolbar contains various buttons for building, running, and debugging your code.
  4. Terminal:
    • CLion includes an embedded terminal. You can access it at the bottom of the window.

Step 4: Writing Code

  1. Code Assistance:
    • CLion provides intelligent code completion, syntax highlighting, and quick-fix suggestions.
  2. Refactoring:
    • Use the built-in refactoring tools to improve your code structure.
  3. Navigation:
    • Navigate through your code efficiently using shortcuts and the “Navigate” menu.

Step 5: Building and Running

  1. Build Configuration:
    • Configure build options in the CMakeLists.txt file.
  2. Build and Run:
    • Use the toolbar or shortcuts to build and run your code.

Step 6: Debugging

  1. Setting Breakpoints:
    • Click on the gutter to set breakpoints in your code.
  2. Debugger:
    • Use the debugger to step through your code, inspect variables, and identify issues.

Step 7: Version Control

  1. Version Control Integration:
    • CLion has built-in support for popular version control systems like Git. Initialize your project with version control if needed.
  2. Commit Changes:
    • Commit and push changes directly from the IDE.

Step 8: Plugins and Extensions

  1. Install Plugins:
    • Explore and install plugins to enhance CLion’s functionality.
  2. Customization:
    • Customize the IDE to suit your preferences, including themes and keymaps.

Step 9: Learning Resources

  1. Documentation:
    • Refer to the official CLion documentation for in-depth information.
  2. Community:
    • Join the CLion community forums and interact with other users.

Congratulations! You’ve completed a basic tutorial on CLion. This should give you a solid foundation for using this powerful IDE for C and C++ development.

Let’s setup a concrete example

Create or Open a project

  • To open an existing project:
  • Start the project with Shift + F10.
  • If you run into Trust error, just click on TRUST PROJECT
  • You can close projects when finished via file > Close Project.

Configuration

Toolchain checking

  • For Windows, a Microsoft Visual environment-based tool-chain is supported.
  • If you have Microsoft Visual Studio Community 2017 installed, the tool-chain should auto-detect.
  • To check or adjust your tool-chain:
    • Go to File.
    • Enter Settings.
    • Access Build, Execution, Deployment.
    • Visit Toolchains.

Build options

  • Creating build profiles with “Debug” and “Release”
    • Settings and Build, Execution, Deployment.
    • Click on CMake, then the + symbol to add a “Release” profile.
  • Set the CMake generator with -G "Visual Studio 15 2017 Win64" and specify the build directory.
  • If using open-cv, add just after : -Wno-dev -DGPU_COMPUTE_CAPABILITY="7_5" -DBIN_CONFIG_TYPE="Release"
  • Set the build directory to build\Release
  • Do the same debug with DBIN_CONFIG_TYPE="Debug"
  • Set Debug as default
  • Toggle between “Release” and “Debug” in the Configurations section.

After this, you can switch between Release and Debug in the Configurations section in the top-right of the window.

Do not forget to setup your dev environment for better coding efficiency.

Plugin & extesions

  • Code With Me: Collaborative development plugin that allows real-time coding sessions with remote team members.
  • MarkDown Support: Enables Markdown file editing directly within CLion for documentation and readme files.
  • Grep Console: Enhances console output with advanced search and highlighting capabilities.
  • Key Promoter X: Helps you learn keyboard shortcuts by displaying mouse actions and suggesting corresponding keyboard shortcuts.
  • Toml: Provides support for TOML file format, commonly used for configuration files.
  • BashSupport: Adds support for Bash scripts, including syntax highlighting and code navigation.
  • PlantUML Integration: Allows you to create UML diagrams in PlantUML format directly in your codebase.
  • Docker Integration: Simplifies Docker container management and integration with your development workflow.
  • CodeGlance: Adds a code minimap on the right side of the code editor for quick code navigation.
  • Power Mode II: Adds a visual effect to your typing, making coding a more dynamic and engaging experience.
  • Rainbow CSV: Enhances CSV file readability by colorizing columns for better visualization.
  • Database Tools and SQL Support: CLion provides built-in support for connecting to databases and running SQL queries. Ensure you have the necessary drivers installed.
  • ClangFormatIJ: For source code formatting.
  • Material Theme UI: For a Material Design look.
  • CMake simple highlighter: Syntax highlighting for CMake; for more features, there’s CMake Plus.
  • Conventional commit: For a clear commit history.
  • SonarLint: Static code analysis to identify and fix coding errors with guidance.
  • GitToolBox: Incorporates git information into code.
  • Rainbow Brackets: Color-codes brackets for readability.

Naming Convention and Code Formatting

  • CLion integrates CLangFormat for code formatting, though bugs may occur.
  • To prevent issues, install the CLangFormatIJ plugin and LLVM for a robust tool-chain.
  • You can customize code formatting using a .clang-format or _clang-format file in YAML.

Formatting C/C++ Code using Clang-Format with Linux

Introduction

In collaborative coding projects, maintaining a consistent coding style across different contributors is crucial. Code formatting tools like Clang-Format are widely employed to achieve this uniformity.

Installation
$ sudo apt-get install clang-format
Format Configuration

Name a file .clang-format and run:

$ clang-format -style=llvm -dump-config > .clang-format

-style can be :
– google
– chromium
– mozilla
– webkit
– microsoft

---
Language:        Cpp
# BasedOnStyle:  LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
  Enabled:         false
  AcrossEmptyLines: false
  AcrossComments:  false
  AlignCompound:   false
  PadOperators:    true
AlignConsecutiveBitFields:
  Enabled:         false
  AcrossEmptyLines: false
  AcrossComments:  false
  AlignCompound:   false
  PadOperators:    false
AlignConsecutiveDeclarations:
  Enabled:         false
  AcrossEmptyLines: false
  AcrossComments:  false
  AlignCompound:   false
  PadOperators:    false
AlignConsecutiveMacros:
  Enabled:         false
  AcrossEmptyLines: false
  AcrossComments:  false
  AlignCompound:   false
  PadOperators:    false
AlignConsecutiveShortCaseStatements:
  Enabled:         false
  AcrossEmptyLines: false
  AcrossComments:  false
  AlignCaseColons: false
AlignEscapedNewlines: Right
AlignOperands:   Align
AlignTrailingComments:
  Kind:            Always
  OverEmptyLines:  0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
AttributeMacros:
  - __capability
BinPackArguments: true
BinPackParameters: true
BitFieldColonSpacing: Both
BraceWrapping:
  AfterCaseLabel:  false
  AfterClass:      false
  AfterControlStatement: Never
  AfterEnum:       false
  AfterExternBlock: false
  AfterFunction:   false
  AfterNamespace:  false
  AfterObjCDeclaration: false
  AfterStruct:     false
  AfterUnion:      false
  BeforeCatch:     false
  BeforeElse:      false
  BeforeLambdaBody: false
  BeforeWhile:     false
  IndentBraces:    false
  SplitEmptyFunction: true
  SplitEmptyRecord: true
  SplitEmptyNamespace: true
BreakAfterAttributes: Never
BreakAfterJavaFieldAnnotations: false
BreakArrays:     true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
ColumnLimit:     80
CommentPragmas:  '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat:   false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
  - foreach
  - Q_FOREACH
  - BOOST_FOREACH
IfMacros:
  - KJ_IF_MAYBE
IncludeBlocks:   Preserve
IncludeCategories:
  - Regex:           '^"(llvm|llvm-c|clang|clang-c)/'
    Priority:        2
    SortPriority:    0
    CaseSensitive:   false
  - Regex:           '^(<|"(gtest|gmock|isl|json)/)'
    Priority:        3
    SortPriority:    0
    CaseSensitive:   false
  - Regex:           '.*'
    Priority:        1
    SortPriority:    0
    CaseSensitive:   false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: false
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth:     2
IndentWrappedFunctionNames: false
InsertBraces:    false
InsertNewlineAtEOF: false
InsertTrailingCommas: None
IntegerLiteralSeparator:
  Binary:          0
  BinaryMinDigits: 0
  Decimal:         0
  DecimalMinDigits: 0
  Hex:             0
  HexMinDigits:    0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
KeepEmptyLinesAtEOF: false
LambdaBodyIndentation: Signature
LineEnding:      DeriveLF
MacroBlockBegin: ''
MacroBlockEnd:   ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PackConstructorInitializers: BinPack
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
PPIndentWidth:   -1
QualifierAlignment: Leave
ReferenceAlignment: Pointer
ReflowComments:  true
RemoveBracesLLVM: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SortIncludes:    CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
  AfterControlStatements: true
  AfterForeachMacros: true
  AfterFunctionDefinitionName: false
  AfterFunctionDeclarationName: false
  AfterIfMacros:   true
  AfterOverloadedOperator: false
  AfterRequiresInClause: false
  AfterRequiresInExpression: false
  BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpacesBeforeTrailingComments: 1
SpacesInAngles:  Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
  Minimum:         1
  Maximum:         -1
SpacesInParens:  Never
SpacesInParensOptions:
  InCStyleCasts:   false
  InConditionalStatements: false
  InEmptyParentheses: false
  Other:           false
SpacesInSquareBrackets: false
Standard:        Latest
StatementAttributeLikeMacros:
StatementAttributeLikeMacros:
  - Q_EMIT
StatementMacros:
  - Q_UNUSED
  - QT_REQUIRE_VERSION
TabWidth:        8
UseTab:          Never
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
  - BOOST_PP_STRINGIZE
  - CF_SWIFT_NAME
  - NS_SWIFT_NAME
  - PP_STRINGIZE
  - STRINGIZE
...
Format Code
$ clang-format -i *.cpp

To format all relevant files (.h, .c, .hpp, .cpp, .cu) together, execute:

$ find . -regex '.*\.\(cpp\|hpp\|cu\|c\|h\)' -exec clang-format -style=file -i {} \;

Check Lei Mao for more.

Feel free to read our article on standard-version which is a powerfull way to keep track on your applications version.

Written by

Albert Oplog

Hi, I'm Albert Oplog. I would humbly like to share my tech journey with people all around the world.