Quantcast
Channel: CLion : A Cross-Platform IDE for C and C++ | The JetBrains Blog
Viewing all 678 articles
Browse latest View live

CLion 2021.2 EAP: Many Debugger Updates and Fixes for CMake Presets

$
0
0

The CLion 2021.2 Early Access Program was recently launched. Did you manage to try out the new Load CMake Presets feature? Or did you play with Cling, an interactive C++ interpreter now supported in CLion? We really hope you managed to catch a few dangling pointers or references with the help of recently introduced Lifetimes analysis.

Today we are happy to announce the second EAP build (212.3724.2), which is now available from our website, via the Toolbox App, or as a snap package (if you are using Ubuntu). Note that if you are on macOS, there is a separate build for Apple Silicon (M1 chip).

Please read on for more details about the changes, give them a try, and share your feedback with us!

DOWNLOAD CLION 2021.2 EAP

Debugger

This EAP build brings a few notable enhancements in the Debugger.

In addition to this list, a few GDB-related issues were fixed: CPP-24874, CPP-24730.

Relaxed breakpoints

This change means CLion now uses the base name of the source file instead of its absolute path. This may be useful in cases where path mappings are too complex to fill them in in the debug configuration or when the -fdebug-prefix-map option is set in the debugger (CPP-15850).

To enable this, right-click the breakpoint and in the context menu select Use file name only to make this particular breakpoint relaxed:
Relaxed breakpoints
CLion will set it using just the file name in GDB or LLDB (depending on which backend you are using). In some projects that might lead to a situation where breakpoints match to several files with the same name, so the debugger will stop in all of these locations.

Run in external console on Windows

CLion uses an internal console to Run/Debug configurations, which caused a set of issues with flushing the output, as well as performance, on Windows. A new checkbox Run in external console is now available in Run/Debug configurations. When selected, CLion will use the cmd.exe console to run and debug applications.
Run in external console

This works for MSVC+LLDB and MinGW+GDB.

Preview Tab now works in Debugger

When the debugger steps through the codebase, new files are often opened in the editor. After a few stepping iterations your editor might be polluted with such files and the tab limit can be exceeded. The preview tab can help here!

The preview tab allows you to view files in a single tab one by one without opening each file in a new tab. You can enable it in Settings/Preferences | General | Editor Tabs | Opening Policy:
Opening Policy

When enabled, it now also works during debugging, so the files you step through, or navigate to using single-click in the frames view or using “prev/next frame” actions, are always opened in a single tab (with its name in italic):
Preview Tab in Debugger

Core Dump: Support debugging Windows minidumps

CLion now supports postmortem debugging with core dumps on Windows, which are known as minidumps. A Windows minidump is a small file that is saved to the disk when the process crashes. This file is stored in the C:\Windows\minidump or C:\Winnt\minidump directory, depending on your version of Windows. To debug it in CLion, use the Run | Open Core Dump action from the main menu.

When you start a core dump debug session, CLion opens the corresponding source code and the Debug tool window automatically. Similarly to a regular debug session, you can use the Frames tab and the Variables pane, as well as Memory and Disassembly view.

Remote LLDB

GDB Remote Debug is a great way to debug remotely any arbitrary executable with debug information in CLion. With this configuration, you can remotely debug applications that were built by any build system. The only requirement is for the debug symbols to be present on the local machine. This is now available for LLDB remote debug on macOS and Linux (remote debugging with LLDB is not supported on Windows currently).

GDB Remote Debug configuration was renamed to Remote Debug to serve both LLDB and GDB remote debug cases:
Remote LLDB
Select LLDB in this configuration and provide arguments to connect to the remote host.

On the remote host you need to start lldb-server, like

lldb-server g *:1234 ./binary

On macOS use debugserver as lldb-server:
debugserver 0.0.0.0:1234 ./binary

1234 is just a sample port we used here.

A few important notes:

  • If you debug from macOS to Linux or from Linux to macOS with LLDB, cross-compilation is the easiest way to get everything working (for example, you can use musl). Otherwise, LLDB is unable to download system libraries automatically.
  • Don’t forget to copy debug info along with binary to the local host to be able to debug correctly.

You can learn more about LLDB remote debugging here. We’ll update CLion’s online documentation soon to help you with the configuration process.

Breakpoints in disassembly view

Disassembly view in CLion was enhanced and now allows you to set breakpoints in it. Add/remove breakpoints on instruction lines the same way you do in the source code:
Breakpoints in disasm

These are address breakpoints. The right-click context menu shows the settings available for them:
Address Breakpoints
When the debugging session is stopped, these breakpoints are removed automatically, because most of the time the address layout changes on the next launch. This behaviour is similar to watchpoints.

CMake Presets enhancements

In the previous 2021.2 EAP build, we introduced initial support for CMake Presets. To briefly reiterate how it works, the Load CMake Presets action searches through the existing Build Presets, shows them to the user, and allows the user to import them into CLion CMake Profiles.

In this EAP, preset loading was simplified significantly.

  • All build presets found in the project are now loaded automatically on project opening in CLion. A few important things to note:
    • All new presets loaded into CMake Profiles are disabled by default, unless you have already loaded and enabled them before (CLion matches them by name).
    • All previously loaded presets are removed from CLion configuration if they are not present in the CMakePreset.json or CMakeUserPresets.json files.
    • CLion loads all build presets it finds in the CMakePreset.json and CMakeUserPresets.json files in the project root.
    • This only happens on project opening.
  • Auto-save now works for preset JSON files, so you don’t need to worry about saving them manually before reloading the presets.

Previously, all loaded presets got a Default toolchain linked to the corresponding CMake Profiles. This might not be appropriate for most cases, so we added the ability to select a toolchain already configured in CLion for a preset. To configure it, use the vendor specific fields in configure preset:

"vendor": {
        "jetbrains.com/clion": {
          "toolchain": "Clang10"
        }
}

When this preset is loaded in CLion, it gets the proper toolchain assigned:
Toolchain in presets

We also fixed some issues for preset arguments containing spaces (CPP-25203).

We hope that this makes your experience with CMake Presets in CLion much smoother, and we’ll keep polishing the support further! Let us know if you are using CMake Presets already and how useful is the CLion support for you.

The full release notes are available here.

DOWNLOAD CLION 2021.2 EAP

Your CLion team
JetBrains
The Drive to Develop


7 Top Tips for Debugging C++

$
0
0

Today we have Greg Law with us. In this guest blog post, Greg will share a few top tips for debugging C++ code.

Greg Law Greg (@gregthelaw) is the co-founder and CEO at Undo. He is a programmer at heart, but likes to keep one foot in the software world and one in the business world. Greg finds it particularly rewarding to turn innovative software technology into real business development. Greg has over 20 years of experience in both academia and innovative startup software companies.

Brian Kernighan famously said, “Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?”. For me, this doesn’t just mean “keep it simple.” It also means debugging is central to programming – you cannot be a great programmer without being great at debugging. Hopefully, my favorite C++ debugging tips will help you be as clever and productive debugging your code as you are writing it in the first place.

#1 Have a full kit of debugging tools

All else being equal, a better-equipped developer will avoid and resolve defects faster than one who is less well equipped. Here are 4 categories of debugging tools that I recommend every programmer should know how and when to use. I’ve included commercial and free open-source options for you to explore:

Category What it tells you Example tools
Interactive debugger Pause execution and explore “What’s my program doing?” GDB, strace
Time travel debugger Step backward and forward through execution time to see how your program arrived where it did. UDB, rr, WinDbg
Dynamic code checkers Analyze or instrument your code to check for buffer overflows and other defects. Valgrind, ASan
Static code checkers Analyze your code to determine whether there’s a risk of specific defects occurring. Clang Analyzer and Clang-Tidy, Coverity, Cppcheck, IDE built-in linters

In this ACCU talk, Dewang Li of Coverity and I go through these categories of tools and explain how they work under the hood.

CLion Debugger tips from Anastasia: CLion doesn’t only let you debug your code with GDB or LLDB backends. It also helps with other tools, including Valgrind and Sanitizers integration, as well as various options for static code analysis.

#2 Conditional breakpoints

A breakpoint lets you stop the execution of the program at a specific line or function in your code. Once your program hits a breakpoint, it waits for instructions from you to inspect or manipulate the application state, resume execution, etc.
To help debug more efficiently, I’m fond of using conditional breakpoints. Instead of pausing every time the breakpoint is reached (which can be tedious if the breakpoint is defined within a loop), I can define a condition for a breakpoint that stops the execution if met. For example, if variable “i” normally equals zero, maybe I want to break if “i” is not zero:

(gdb) break my_func if i!=0

You can write pretty much any condition you want in the programming language of the program you’re debugging, which makes conditional breakpoints very powerful and efficient. The condition can include a function call, the value of a variable, or the result of any GDB expression.
To learn more, check out this video tutorial, in which I explain conditional and various other breakpoint types, and how to use each of them in your debugging.

CLion Debugger tips from Anastasia: In CLion you can easily specify a condition that is checked each time a breakpoint is hit.

#3 Watchpoints

Like breakpoints, a watchpoint stops execution, but does so whenever the value of an expression changes, without having to predict a particular line of code where this may happen. Watchpoints are extremely helpful when debugging concurrency issues, like when trying to understand what thread or process is changing a shared resource. The expression may be as simple as the value of a single variable, or as complex as many variables combined by operators. Examples include:

  • A reference to the value of a single variable.
  • An address cast to an appropriate data type. For example, *(int *)0x12345678 will watch a 4-byte region at the specified address (assuming an int occupies 4 bytes).
  • An arbitrarily complex expression, such as a*b + c/d. The expression can use any operators valid in the program’s native language (see Languages).

Here’s a blog post and video demonstrating how to use different types of watchpoints.

CLion Debugger tips from Anastasia: If you are wondering how to add a watchpoint in CLion, check out the webhelp.

#4 User-defined debugging commands in Python

I recommend tailoring your debugger to fit your project and team. In GDB, this can be done by creating user-defined commands in Python. You can do all kinds of smart things to help make detecting (and resolving) thorny bugs a breeze. Plus, there are lots of other tricks you can do to customize GDB to your particular project and debugging needs.
Not taking advantage of Python is something you may regret later – a missed opportunity to increase your debugging speed, not to mention your general quality of life! It’s a small investment in time that pays back quickly and, over time, significantly.
For example, you can automate a task like checking debugger output into source control and sharing it with your teammates. In this blog post, I show how the Python integration with GDB can be used to do exactly that.

CLion Debugger tips from Anastasia: Did you know that during a debug session, you can access the GDB/LLDB console directly from CLion? The tab shows the debugger’s output/error stream and lets you run GDB/LLDB commands.

#5 Pretty-print structures

Printing variables, structures, and classes is a big part of debugging. By default, the debugger might not print the value in a way that makes it easy for the developer to understand.
For example, when I print the siginfo_t structure, the print command returns all the data in the structure, including expanding the unions it uses:
Messy and not easy to read!
Fortunately, GDB can be extended with “pretty-printer” functions. When GDB prints a value, it checks whether there is a pretty-printer registered for that value. If so, GDB uses it to display the value. Otherwise, the value prints in the usual way.
It takes a little coding up front to create the pretty-printer function, but I promise it will save you so much time staring at your computer screen. Here’s a video in which I demonstrate a quick way to pretty-print structures in GDB.

CLion Debugger tips from Anastasia: If you add custom pretty-printers to GDB, CLion will use them by default.

#6 Time Travel Debugging

Very often, you need to know what your program actually did, as opposed to what you expected it to do. This is why debugging typically involves reproducing the bug many times, slowly teasing out more and more information until you pin it down.
Time Travel Debugging takes away all that guesswork and trial and error – the debugger can tell you directly what just happened.
Free debuggers like GDB have built-in Time Travel Debugging capability. It works pretty well, but you have to be ready to sacrifice performance (a lot of it). Commercial, purpose-built time travel debuggers like UDB offer much faster Time Travel Debugging performance.
The process is like regular debugging except that you can step/continue back in time. Breakpoints and watchpoints work in reverse, which can help you, for example, to continue directly to a previous point in the program at which a specific variable changes. Reverse watchpoints can be incredibly powerful. I know of several instances of bugs that eluded a developer for months or even years that were solved in a few hours with the power of reverse watchpoints.
In this video, I demonstrate reverse debugging in GDB. Check it out: it shows you step by step (in reverse) how to trace a fault in my program.

CLion Debugger tips from Anastasia: Undo has created a CLion plugin for UDB Time Travel Debugger. See our previous collaborative post with the Undo team for more details.

#7 Command find to search for a byte sequence

Sometimes when you’re debugging, you need to find a particular sequence of bytes in the memory space of the program. Perhaps you want to see all the pointers to a specific object. So, every eight bytes in memory that corresponds to the byte sequence is an address you want to identify.

The find command in GDB offers you a different kind of inspection into your program. All search values are interpreted in the programming language of the program. For example, the source language of hello.c is C/C++; so if we search for the string “Hello, world!”, it includes the trailing '\0'.

GDB also provides information about the memory mappings of program processes, which helps you focus the search in certain segments of the program’s memory. The address of each match found is returned, as well as a count of the number of matches.

Want more C++ debugging tips?

I’ve shared seven tips for better C++ debugging productivity. Hopefully they help you out – sometimes little tweaks to your usual debugging habits and routines can make a big difference. And let’s share! I’d love to hear your top tips as well. You can reach me on Twitter or find me on LinkedIn.
Here are some resources to help you on your path to better debugging:

  • GDBWatchpoint – Subscribe to my blog on undo.io
  • Get GDB – free C/C++ debugger
  • UDB – Commercial time travel debugger (free 30-day trial)

And from the JetBrains side, here are a few more resources for CLion:

Thank you, Greg, for sharing these useful tips!

And a question to our audience: what is your favorite debugger tip? Please share in the comments!

JetBrains Brings C++Now to You

$
0
0

Hi all,

C++Now is generally regarded as the year’s most academic event in the C++ community. The conference hosts excellent talks from some of the most prominent experts in the community about cutting-edge C++ language features and advanced C++ skills.

Participants usually come together in person for the meeting in Aspen, Colorado, US. As I once commented, “At the altitude of 2,400 meters, C++Now offers limited oxygen but unlimited C++ insights.”

Unfortunately, the 2020 event was cancelled because of the pandemic. But in 2021 the conference was back! It took place online May 2–7, 2021, and kept all its most distinctive qualities in the new format. C++Now 2021 brought discussions of some of today’s hottest topics, like C++ ABI stability, CMake, C++20 modules and concepts, and more.

Don’t be upset if you missed the event. JetBrains has been a proud video sponsor of C++Now for several years, and this year we’re offering early access to the conference recordings!

C++Now recordings

We will be publishing the talks over the course of several weeks on this page: http://jb.gg/cppnow. All the presentations will later be available on C++Now’s official YouTube channel. Can’t wait to watch the first recordings from the event? The first talks are already available on the page, and more recordings are coming in the next month!

The JetBrains C++ team
The Drive to Develop

CLion 2021.2 EAP: Updates to Remote Development Mode, Debugger, and CMake Presets

$
0
0

A new CLion 2021.2 EAP build (212.4037.2) is now available from our website, via the Toolbox App, or as a snap package (if you are using Ubuntu). Note that if you are on macOS, there is a separate build for Apple Silicon (M1 chip).

Please read on for more details about the changes, give them a try, and share your feedback with us!

DOWNLOAD CLION 2021.2 EAP

Here are the main highlights:

Remote development in Docker without source synchronization

A new setting now provides a way to configure and use docker containers for remote development in CLion without unnecessary source synchronization. This improves the remote development experience in Docker in several ways:

  • No initial project upload to Docker
  • No code duplication (previously, one copy of the project was local and one was in Docker)

Here is how to set up remote development without source synchronization:

  1. Configure a Docker container with mapped volumes:
    Docker configuration
  2. Set up a remote toolchain in CLion.
  3. Go to Build, Execution, Deployment | Deployment settings and change the connection type to Local or mounted folder:
    Remote docker
  4. Then fill in the path mappings with the mapped volumes:
    Remote mappings
  5. Now you can use this remote Docker toolchain for your CMake or Makefile remote projects.

Finally, this should also work not just for Docker, but in general when you have your local and remote machines sharing a mounted volume or when 3rd-party synchronization is configured outside of CLion. We haven’t tested it carefully yet, but you can try it out and share your feedback with us.

More CMake Presets enhancements

In the first 2021.2 EAP build, we introduced initial support for CMake Presets. Later we added some improvements, like loading build presets automatically when you open your project in CLion. In this EAP build we’ve fixed some NullPointerException and MalformedJsonException issues when parsing the preset, and we’ve forced the Reload CMake action to fetch changes in presets, if any.

The option to specify a source file during the debug session

The previous EAP build brought a whole set of significant enhancements to the debugger, like relaxed breakpoints, remote LLDB, the ability to debug core dumps on Windows, and others.

In this EAP build, we’ve addressed the case where CLion can’t find the source files during the debug session. This might happen when you debug a custom executable using some fake project or when there is some library built on CI without the source code being in the project. Stepping to these source locations will cause the disassembly view in CLion, as the IDE can’t locate the actual source code. Now you can explicitly specify where to find the source files. The notification is shown in the disassembly view:
Specify source in debugger

Update notifications from the Toolbox App

Do you use the Toolbox App to manage CLion installations and updates? Now you won’t miss any critical product updates from it. Your IDE will inform you if there is a new version available for download and give you the option to upgrade right from CLion. You’ll need to have Toolbox App 1.20.8804 or later for this.
Updates from Toolbox App

The full release notes are available here.

DOWNLOAD CLION 2021.2 EAP

Your CLion team
JetBrains
The Drive to Develop

CLion 2021.2 EAP: Improved Natvis Support and FreeRTOS Thread View

$
0
0

The CLion 2021.2 EAP is in full swing. In the last few weeks we’ve already presented CMake Presets support, Lifetime analysis, Cling interpreter integration, various debugger enhancements, and improvements for Docker workflow. This week, we’re giving you a massive update for the LLDB-based debugger on Windows that improves Natvis support, as well as a FreeRTOS thread view!

The new build (212.4321.2) is now available from our website, via the Toolbox App, or as a snap package (if you are using Ubuntu). Note that if you are on macOS, there is a separate build for Apple Silicon (M1 chip).

DOWNLOAD CLION 2021.2 EAP

Here are the main highlights:

FreeRTOS thread view

FreeRTOS is a real-time operating system for microcontrollers. If you debug applications with it in CLion, you can now get a view with the task lists. You can switch to the task you are interested in to explore task variables and more.

To get the FreeRTOS thread view, turn it on in Settings/Preferences | Build, Execution, Deployment | Embedded Development | RTOS Integration:

RTOS settings

You also need GDB version 7.4 or higher with Python support. You can use the GDB that is bundled in CLion. This is intended to work for any relevant Run/Debug configuration.

As an example, let’s take this project and the QEMU emulator, create an Embedded GDB Server configuration, and pass the following arguments to the GDB server:

-cpu cortex-m3 -M lm3s811evb -nographic -gdb tcp::1234 -S

RTOS configuration sample

Let’s now launch the debugger and explore the FreeRTOS thread view:
RTOS in action

We plan to add more information to this view, like queues, semaphores, mutexes, and timers (CPP-17219).

If there is anything else you need that’s missing from this view, please let us know!

Improved Natvis support

CLion comes with an LLDB-based debugger for the Microsoft Visual C++ toolchain (MSVC). If you have custom native visualizers in your project, CLion will use them. For a while now we’ve been working on improving Natvis support in CLion and this build brings lots of valuable enhancements.

The following Visual Studio Natvis customization features are now supported:

  • Inheritable attribute, which specifies whether a visualization applies only to a base type, or to a base type and all derived types.
  • Format specifiers, which control the format in which a value is displayed.
  • CustomListItems, allowing you to write custom logic for traversing a data structure.

Built-in renderers:

  • CLion now automatically generates one-line summaries for all structures not covered by Natvis. And summaries are now colored to increase readability.
  • CLion shows the [Raw View] for Natvis-generated values.
  • Built-in formatters are enabled for wide/Unicode strings (wchar_t, char16_t, char32_t).

And other fixes:

  • Enabling the variable sort affects only the top-level and preserves the member order in classes.
  • When you tried copying a selection of variables in our LLDB-based debugger on Windows, some of the data would not be copied. The issue has now been fixed.
  • We’ve implemented a fix for the incorrect rendering of the tuple collection (CPP-21763).

Natvis updates

There is also a pack of improvements for rendering Unreal Engine objects. You can try them in this CLion EAP or in the upcoming Rider for Unreal Engine Preview build, as both tools share the same debugger that our team implements.

And other enhancements

As usual, this build also addresses many functional, UI, and performance glitches and problems.

In Unit Testing support:

  • We’ve addressed the issues causing Boost.Test suites not to be found (CPP-15546).
  • The test tree for Boost.Test is now shown before the actual test execution.
  • Boost.Test integration now supports decorators, such as boost::unit_test::disabled()/enabled().
  • A regression has been fixed that was causing run icons for Catch not to be updated with the test status (CPP-25428).

As you might know, CLion supports CMake, Makefile, Gradle, and compilation database as project models. You can also open a project in CLion without loading a project model. In this case, you can still load the project model later. For this, CLion has the Load CMake Project context action for CMakeLists.txt.

We’ve now added a similar action for Makefile – Load Makefile Project:
Load Makefile project

The typical use case is for Makefile projects that require some preconfigure step or launching some script to prepare the final Makefile, so you might not have it from the very beginning when opening your project in CLion. You can now open such a project simply as a folder, launch the necessary script from the built-in terminal, and then load the Makefile with this context action.

The full release notes are available here.

DOWNLOAD CLION 2021.2 EAP

Your CLion team
JetBrains
The Drive to Develop

CLion 2021.2 EAP: Profiling in Remote Mode, Enhancements for Cling and CMake Presets

$
0
0

The new CLion 2021.2 EAP (build 212.4416.11) is now available from our website, via the Toolbox App, or as a snap package (if you are using Ubuntu). If you are on macOS, there is a separate build for Apple Silicon (M1 chip).

Starting with this EAP, you can join the program only if you have an active JetBrains account. If you have already logged in with your credentials, you can access the EAP builds automatically. If you have not yet logged in, the IDE will redirect you to account.jetbrains.com where you can enter your login and password or create a new JetBrains account. Learn more in this blog post.

DOWNLOAD CLION 2021.2 EAP

Here are the main highlights:

Profiling in remote mode

CPU profiler integration previously only worked for local setups on Linux and macOS, but we have enabled it for remote mode.

In remote mode, only Linux is allowed for the OS of the remote host, which means profiling will work through the Perf backend.

Find instructions in our webhelp on how to install the Perf tool for your particular kernel release. You also need to configure the path to the Perf tool in CLion Settings/Preferences | Build, Execution, Deployment | Dynamic Analysis Tools | Perf:
Perf settings

After launching the profiler, CLion notifies you if the profiler is attached successfully and when the profiling data is ready:
Profiling data collected

In the CPU Profiler tool window, you can explore the collected data:
Profiling results

In the next EAP build we’ll also enable profiling on WSL. So stay tuned!

Cling enhancements

Cling, an interactive C++ interpreter, was already added to CLion in an earlier EAP build. It makes learning C++, inspecting libraries, and prototyping quick and easy. Starting with this EAP build, Cling sessions in CLion start up with the flags collected for the file that is currently open in the editor. This applies to both language standards and include paths.

We’ve also made it easier to set working directories in the Cling session:

  • If there is a file currently open in the editor, we use its directory as a working directory for Cling, so related include paths from this file should work when sent to the Cling session via Alt+Enter.
  • Otherwise, CLion uses the project root.
  • Otherwise, if there is no project, CLion uses the user’s home directory.

Fixes for CMake Presets

We are continuing to work on CMake Presets in CLion. This build brings a set of important fixes:

  • Error reporting has been improved. CLion now displays error details on the Project Errors tab of the Problems view.
  • Actions like Reset Cache and Reload and Load CMakeLists.txt now load CMake Presets.

Besides, there are a few VCS and Space integration changes. The full release notes are available here.

DOWNLOAD CLION 2021.2 EAP

Your CLion team
JetBrains
The Drive to Develop

CLion 2021.2 EAP: Profiling on WSL, Fixes for CMake Presets, LLDB 12

$
0
0

The new CLion 2021.2 EAP (build 212.4535.17) is now available from our website, via the Toolbox App, or as a snap package for Ubuntu. If you are on macOS, there is a separate build for Apple Silicon M1 chip.

DOWNLOAD CLION 2021.2 EAP

Here are the main highlights:

Profiling on WSL

CPU profiler integration previously only worked for local setups on Linux and macOS, and was enabled for remote mode in a previous EAP build. Now, it also works on WSL.

You will need a Perf backend, and you can only install it on WSL 2.

We hope that enabling profiling on WSL will help Windows users who are suffering from the lack of profiling abilities in CLion. In the future, we may also add a native profiler for our Windows users.

CMake Presets fixes

We’re continuing our work on CMake Presets in this release cycle. This time, we’ve added the following enhancements:

  • When you edit the preset in CLion (as a json file) or update it externally, CLion will notice the change and will suggest a CMake Reload to get the changes:CMake Presets Reload
  • On Windows, architecture and toolset properties from the configure preset are now passed to the CMake options in the CMake profile on import:Windows toolsets and arch

LLDB 12.0

CLion now bundles LLDB v12.0. Please let us know if you observe any issues with this debugger version.

Doxygen

You can now configure the colors that are used in Doxygen comments in Settings/Preferences | Editor | Color Scheme | C/C++ | Comments | Doxygen:
Doxygen colors

The full release notes are available here.

DOWNLOAD CLION 2021.2 EAP

Your CLion team
JetBrains
The Drive to Develop

CLion 2021.1.3 Bug-fix Update With Fixes for CUDA and More

$
0
0

A new CLion 2021.1.3 bug-fix update is available! Download build 211.7628.27 from our website, get an update via the patch, update in the Toolbox App, or snap (for Ubuntu).

The highlights include:

  • Fixes for CUDA:
    • Fixed red CUDA code with Visual Studio C++ toolchain (CPP-25687).
    • Fixed the code completion in CUDA code that stopped working after including a normal C++ header file (*.h) to the CUDA files (CPP-25144).
    • Fixed the incorrect error Use of undeclared identificator __cudaPushCallConfiguration (CPP-25157).
  • IntelliJ-platform fixes:
    • JetBrains Runtime was updated to 11.0.11-b1341.60, which includes many UI fixes.
    • CLion no longer shows update notifications from disabled plugins (IDEA-267878).
    • Ctrl+Shift+Arrow keys work for text selection as it should, instead of resizing the dialog by mistake (IDEA-267294).
    • Fixed an unexpected closure of the Compare with branch dialog (IDEA-251381).

You can find the full release notes here. If you haven’t updated to v2021.1, now is a great time to do so. Check out the 2021.2 EAP if you are interested in what’s coming next.

DOWNLOAD CLION

Your CLion team
JetBrains
The Drive to Develop


CLion 2021.2 EAP: Support for GNU Autotools (Autoconf, Automake) Projects

$
0
0

The new CLion 2021.2 EAP build (212.4638.8) is now available from our website, via the Toolbox App, or as a snap package for Ubuntu. If you are on macOS, there is a separate build for the Apple Silicon M1 chip.

DOWNLOAD CLION 2021.2 EAP

The landscape of Make-based projects is very diverse, so it was hard to cover all of them at once in CLion. When we first added support for Makefile projects, it was limited to certain kinds – the Makefile had to be present in the project directory, which meant all of the preconfiguration steps had to be called manually before loading and opening the project in CLion. Now it’s time to relax this limitation!

CLion now automatically detects GNU Autotools, Kbuild, and PERL MakeMaker projects. When these projects are loaded as Makefile projects, CLion automatically detects preconfiguration scripts and executes them to get the Makefile and load the project from it.

CLion now covers two scenarios:

  1. If there are configure.ac and Makefile.am in the project, CLion will require GNU Autoconf to be installed in the system (it will search for autoreconf in the system PATH). CLion will generate the Makefile, and use it to load the project.
  2. If there is a configure script and no configure.ac in the project, it will be called by CLion, and no autoreconf is required.

For example, let’s take Make v4.3 and open it in CLion:
Reload Make 4.3

For many projects, that is all you need to open them in CLion!

You can call any additional scripts, like bootstrap, from the built-in terminal, and you can tune additional preconfigure step parameters in Settings/Preferences | Build, Execution, Deployment | Makefile:
Makefile settings

As an example, if you open a recent version of the make project from Git in CLion, you need to call ./bootstrap in the terminal first.

A few known issues are worth mentioning here:

  • Interactive preconfiguration step is not yet supported (CPP-25742).
  • Makefile projects unnecessarily load twice in some cases (CPP-25621).

The full release notes are available here.

DOWNLOAD CLION 2021.2 EAP

Your CLion team
JetBrains
The Drive to Develop

C++ Annotated: June 2021

$
0
0

Welcome to the June edition of C++ Annotated and its companion, the No Diagnostic Required show!

If you are already subscribed, feel free to skip to the news. If you are new, you can explore all the formats we offer. Choose to read, listen, or watch our essential digest of this month’s C++ news:

  • Read the monthly digest on our blog (use the form on the right to subscribe to the whole blog).
  • Subscribe to C++ Annotated emails by filling out this form.
  • Watch the No Diagnostic Required show on YouTube. To be notified of new episodes, follow us on Twitter.
  • Listen to our podcast – just search for “No Diagnostic Required” in your favorite podcast player (see the list of supported players).

June news

Watch the June episode of No Diagnostic Required below, or keep reading for all the latest news!

Language news (guest content from Phil Nash)

June saw another virtual plenary session on the standards committee, the full working-group meeting where papers are voted on for the draft standard. Herb Sutter wrote his regular trip report providing us with highlights, and we’ll look at some of those.

Before we do that, though, it’s worth reflecting on a comment Herb makes about the process still being on the original schedule, and with the original priorities. That means that the next meeting, scheduled for this fall, will be the last one for introducing new features targeting C++23. The meeting after that should be “feature-complete”! With C++20 only recently finalized and compilers still only partially supporting it, this might sound surprising, and even more so when you consider how few features have been voted in so far. But that might be a good thing! C++20 was a big release with some far-reaching features added. We could probably do with more of a “maintenance release” to round out support for those features, fix a few problems that have sprung up around them, and get in a few smaller features if we can. C++23 may finally be the year of modules on the desktop. Or something.

That said, some small – but welcome – changes continue to make it in. Let’s have a look at a few that got in this time.

P1938: if consteval

This one can be seen as addressing an issue with a new C++20 feature. The C++20 feature is std::is_constant_evaluated(). This is currently a “magic” constexpr function that returns true if it is being evaluated at compile time. It’s very useful if you need to do something different depending on how a constexpr function is called (e.g. if an optimized version can’t be made constexpr on its own). Unfortunately, it has two problems!

The first is that it’s very often used incorrectly – in a way that looks intuitive and compiles (possibly with a warning, since this was noted even in the C++20 timeframe). It feels natural to want to use this with if constexpr, like so:

if constexpr (std::is_constant_evaluated()) {
    // slow, but pure version – only this ever gets called
}
else {
    // optimized version, but never executed!
}

The trouble is, when we use if constexpr here, is_constant_evaluated() is always evaluated in the constant context of the if constexpr, regardless of how the enclo
sing function is called! So, in fact, you should just use a normal, runtime if.

That leads to the second issue. Once you’re using a runtime if within the if case, it will only be entered in a compile-time context, but that is still in a context that needs to be valid for runtime. That means that if you refer to an argument to the constexpr function that you’re in, that argument will be runtime if called in a non constant-evaluated context and will fail to compile!

if consteval fixes both these problems by being a more direct way to express the same idea, and which more obviously parallels if constexpr. The usage and semantics are clearer, and the if case is always an “immediate invocation” (i.e. compile-time).

P1659: starts_with and ends_with

We’ve had these as member functions of std::string (and std::string_view) since C++20. Frankly it’s a wonder we had to wait until then for them, but it’s good we finally have them. The other odd thing about them, though, is that they appeared as member functions. Logically they should be separate algorithms and not tied to string types at all. Presumably they were added that way for ergonomic reasons – a battle with a long history, especially for string types. This proposal adds them as range algorithms, and by doing that alone, they are now more easily composable with other algorithms (see the example usage in the paper). However, they also add the ability to specify the comparison operator to use. By default it is ranges:: equal_to, but in some cases (such as numeric sequences) it can be useful to check that a sequence starts with or ends with values that are all greater or less than the comparison sequence.

Finally, the author proposes that changes be made to SD-8 (the Standing Document concerned with compatibility issues) to use range-based algorithms over member functions as a general practice.

P2166: A Proposal to Prohibit std::basic_string and std::basic_string_view construction from nullptr

Talking of std::string and std::string_view, constructing either from a null pointer is undefined behavior and can result in a crash, if you’re lucky, or worse, not do much! If that null pointer is known at compile time, then it is possible to detect such a usage at compile time and raise an error. That’s just what this paper proposes. On the one hand, that seems like a no-brainer. On the other hand, is this really something that happens much in practice? Surely you would notice? And yet the paper cites a number of examples found in highly regarded, high-profile libraries, such as LLVM, Poco, and Protobuf! Of course some of these examples are in generic code, which often obfuscates such things. So if we can rule out such bugs with one simple change, then why not? After all, it just amounts to adding a couple of deleted constructors from nullptr_t.

Having fun with the detection idiom and macros in C++

The detection idiom detects whether certain expressions are valid or ill-formed for given types at compile time. This helps enable specialized implementations of the templated functions. Antoine Morrier presents an implementation that uses macros in the CPP Rendering blog.

While the solution via Concepts described in Sy Brand’s blog might look more elegant and readable, Morrier states that the idea was to get something working, even with C++14, while keeping boilerplate code to a minimum. You’ll find some pattern matching and a recursive macro in the approach, and polymorphic lambdas to get the final macro is_valid that checks whether a given expression is valid. What do you think? Which solution looks more elegant and is easier to read for you?

Measurements of include times for C++ libraries

This CPP-LIT library isn’t new, but it got lots of contributions in June, which is why we paid attention to it and want to share it with you here. The repo answers the question of how much time is added to the compile time with a single inclusion of <header>. It covers C++20 headers, including C++20 module versions of STL. It turned out that inclusion of the standard library in module form was amazingly fast.

To make the measurements accurate and reproducible, a few conditions were met:

  • The lower limit for the header usage was measured, so tests were not actually using the headers, just including them. Times might become significantly longer if you try using heavy templates from some headers.
  • The worst case of sub-includes was measured. That means that every sub-header is included for the first time.
  • Times were measured without any caching (which means no PCH or other approaches were used).
  • The measurements were taken for the RELEASE build with the /std:c++latest flag passed to the compilation.
  • The measurements were taken with Visual Studio 2019 16.11.0 Preview 2.0.

C++ text formatting API

Victor Zverovich, one of the maintainers of the {fmt} library, wrote a blog post on formatting approaches in various languages and in modern C++. It briefly goes through the existing options in various languages, including Python and Rust, and shows the drawbacks of the existing C and C++ approaches. The goal is to show how you can get an extensible format specification checked at compile time with an expected and clear error output in C++.

In the {fmt} library, it’s implemented using C++20’s consteval and doesn’t seem to significantly affect compilation speed. Similar compile-time checks for C++20 std::format have been accepted into the C++ standard and are coming soon.

The big STL algorithms tutorial

Jonathan Boccara once did 105 STL algorithms in less than an hour at CppCon. Sandor Dargo dedicates a blog post to each of the algorithms, so it takes him much longer. The series has already covered modifying sequence operations, sorting operations (except for ranges), and binary search operations.

The June edition features merge and inplace_merge. You can learn that not only both of the ranges must be sorted to be merged successfully (the behavior is undefined otherwise), but also it’s the caller’s job to make sure that the output range has enough space to accommodate all the elements from the two inputs. On the contrary, inplace_merge doesn’t require handling proper space allocation, as it uses the same input for the output.

All articles in the series are accompanied with these small but important details and basic usage examples to help you learn the algorithm.

Switching to Clang improved PVS-Studio’s performance

The PVS-Studio C++ analyzer switched to using the Clang compiler, specifically the Clang-cl compiler on Windows, instead of MSVC. This simple change improved the performance of the analyzer on a set of self tests by 13%!

The most interesting thing in the blog post is the list of things that went wrong and had to be corrected when switching to the Clang-cl compiler:

  • A different set of warnings was produced by MSVC and Clang compilers, so the compilation settings had to be updated.
  • The int128 type is supported out of the box in GCC and Clang compilers, so the preprocessor definition had to be updated where used. The alignment in the structures using this type also had to be corrected to avoid segmentation fault errors.
  • Manually passed the library with built-ins to the linker.

This all reminds me that changing the compiler is not an easy step, especially Clang on Windows. Our team had a similar experience when we were setting up Clang with the Mingw-w64 toolchain in CLion.

CLion 2021.2 EAP comes with an enhanced debugger experience

The CLion 2021.2 Early Access Program is currently running. It started in May with CMake Presets, Lifetime Analysis, and the Cling interpreter. In June, many debugger enhancements were released and they are among our users’ favorite updates in this release cycle.

One great new feature is the ability to use Relaxed Breakpoints. This means CLion will use the base name of the source file instead of its absolute path, and can be useful in cases where path mappings are too complex to use effectively in the debug configuration. The Preview Tab was introduced for the debugger and made it possible to prevent the editor from generating too many tabs when stepping actively through the codebase. The preview tab allows you to view files in a single tab one by one without opening each file in a new tab. You can debug an arbitrary executable with the debug information in CLion with both GDB and LLDB remote debug. On Windows, CLion bundles an LLDB-based debugger implemented by the JetBrains team for the MSVC toolchain. This debugger got a massive overhaul which significantly improved the Visual Studio Natvis customization support.

ReSharper C++ 2021.2 EAP introduces an Inline Function refactoring

It’s good to have refactoring working in both directions, isn’t it? The Extract Method refactoring has been available in ReSharper C++ for a long time. In its 2021.2 EAP, the opposite action – Inline Function – also works. You might want to use it when the function body is obvious, so the code will become clearer if you minimize the number of function calls.

It’s not always possible to inline a function, and in that case ReSharper C++ will let you know with a message like “Cannot inline virtual functions”. When the refactoring is possible, you’ll benefit from a fully automated action that will perform the necessary code transformations, handle all name conflicts for used variables, and reformat the resulting code for you.

Code analysis in CLion with third-party plugins

Code analysis in CLion gives you many options and opportunities to catch various types of errors and inaccuracies. This includes basic compiler checks, Data Flow Analysis catching dangling pointers and other lifetime issues, MISRA-specific Clang-Tidy and Clazy checks, inconsistent naming issues, and more.

Even though the native abilities are strong enough, there are third-party plugins to strengthen the code quality protection. For example, the CppCheck plugin has existed in the plugin repository from the very beginning of CLion’s history. It’s now time for more tools integrated into CLion!

A free SonarLint plugin from SonarSource, the creator of the well-known SonarQube team tool for code analysis, was officially released in May and updated in June. It adds to the MISRA, C++ Core Guidelines, and other modern C++ checks.

There is a plugin for PVS-Studio for CLion open for free beta-testing (you can register and get a trial analyzer key by email). MISRA C and C++ checks, as well as general C++ checks, are available.

News from CppCon 2021

CppCon 2021 will take place October 24–29, both in-person in Aurora, Colorado, USA, and Online! The final details for the event were announced in June, and a call for submissions is now open with a July 19 deadline. If you have a topic on anything related to C++, hurry and submit it to the biggest C++ community event of the year!

Registration is now open! Bjarne Stroustrup will be opening the event and presenting live in Aurora. The talk will be dedicated to the C++20 milestone, which contains all of the features (except the unified function call syntax) that Bjarne described a quarter-century ago in his book “The Design and Evolution of C++”. Big C++20 features are finally starting to be delivered to the major compilers so C++ developers can benefit from them in practice.

A track dedicated to designing quality software components will be launched this year. Everything you want to know about scalable, readable, and maintainable C++ code will be shared there.

And finally, what can C do that C++ can’t?

In early July, a thread on reddit asked the question “After C++17, is there a single C feature that is not possible in C++?” Stable cross-platform ABI specification was the most frequently suggested answer. This is especially interesting in the context of ongoing discussions in the C++ Standardization Committee about breaking the C++ ABI.

The thread also mentions:

  • Simplicity (no surprise here, as lots of current C++ language proposals are targeting simpler language).
  • C bindings for many other programming languages.
  • Compiler support for niche platforms, especially custom embedded compilers. This might be because the C compiler is easier to implement.
  • Easier-to-achieve fast compile times (still achievable with C++ but requires more effort).
  • Designated initializers were mentioned as a specific language feature (delivered in C++20).

And my favorite answer is: “You can spell the name of “c” with a single keystroke!”

CLion 2021.2 Goes Beta!

$
0
0

CLion 2021.2 has reached Beta! Build 212.4746.15 is available from our website, via the Toolbox App, or as a snap package (for Ubuntu).

CLion 2021.2 Goes Beta!

DOWNLOAD CLION 2021.2 Beta

Here are the main highlights:

We’d like to mention a few IntelliJ-platform features that are included in CLion, which we haven’t mentioned before. If you want certain operations to be performed on Save, you can now configure them all in one place in Settings/Preferences | Tools | Actions on Save:
Actions on Save

In v2021.2, we’ve expanded the list of possible pre-commit actions with the ability to execute tests. Tick the Run Tests checkbox and select the configuration to run:
Running tests before commit

You can find the full release notes here.

DOWNLOAD CLION 2021.2 Beta

Your CLion team
JetBrains
The Drive to Develop

C++ Ecosystem in 2021: 1 in 5 C++ developers are using C++20 and a third of us are not writing any unit tests at all, and other facts

$
0
0

The Developer Ecosystem 2021 report is now available!

Every year we ask thousands of developers, with various backgrounds from all around the globe, dozens of questions, which we have localized into many different languages. We then clean, weigh, and process the data carefully, and validate it against other data sources. Our goal is to extract the key trends, which we will present through infographics to the public. This data is used across JetBrains to help our team make the right decisions on both global and product-levels. We are happy to share this data with the community so we can all thrive together!

The full report for 2021 is now available. We invite you to read through the key takeaways and detailed data for many programming languages and areas of software development.

DevEco C++ 2021

Let’s discuss the C++ results with experts!

We’ve invited two guests to join us and take a closer look at this year’s C++ results and what they mean to the C++ community:

We’d like to thank Matt and Andreas for joining the discussion.

We gave our guests early access to the results and asked them about their general impressions on the state of the C++ ecosystem through 3 questions:

  • What was the most surprising data from 2021?
  • Is there anything in the results that you find especially encouraging from the perspective of the evolution of the C++ ecosystem?
  • Is there anything in the results that you find extremely disappointing from the perspective of the evolution of the C++ ecosystem?

I. What was the most surprising data from 2021?

Andreas:
The top-3 surprises for me are:

  • How many people are not using any static analysis or automatic code formatting
  • How many people are still using C++98/C++03
  • GCC is growing more than Clang!

Matt:

  • It is interesting to see open source compilers topping the list of regularly used compilers. In my world, being on Linux makes the MSVC compilers unavailable to me, but I have always thought that the programmers on Windows would outnumber us, and so the MSVC usage would be higher.

II. Is there anything in the results you find especially encouraging from the perspective of the evolution of the C++ ecosystem?

Andreas:
The hype around modules is very encouraging! Better encapsulation and reduced compile times for libraries will be a huge boost to the ecosystem!

Matt:
It is nice to see the adoption of modern C++. 1 in 5 respondents are on the latest standard, which is great, and many more are planning on migrating to at least C++17 in the next year. Modules and concepts seem to be some of the strongest motivators to adopt a newer standard. I’m finding concepts valuable, but I haven’t yet gotten my head around modules, and I’m hoping tooling will help me move to modules as it becomes more widely supported.
Besides that, it’s great to see many people using static analysis.

III. Is there anything in the results you find extremely disappointing from the perspective of the evolution of the C++ ecosystem?

Andreas:
The fragmentation in build systems and package management continues to be an issue. While it’s good to explore different solutions, I think the C++ community can learn a lot from other languages that have chosen to go with a single unified approach to build/package management.

Matt:
It is still disappointing to see that a third of the developers are not writing any unit tests at all.
Nearly 3/4 of respondents are suffering from lack of good packaging solutions – having to build libraries separately, prebuild, or use system package management means either developer toil or reliance on external parties to build them. That can mean getting behind on new versions and it adds complexity to upgrading or changing compilers.

Where is the C++ ecosystem now?

C++ language standards adoption

While there is still a stable audience for C++98/C++03, newer standards are constantly growing and taking developers away from previous versions. This is how the timeline for C++11 and newer standards looks through the years we’ve been running the research:

C++ Srandards

Just to highlight this: in 2021, 1 in 5 C++ developers are using the latest officially signed C++20 standard even though it’s not yet fully supported in all major compilers! Many of us believe that C++20 is the next big release after C++11 and will have a huge impact on the C++ ecosystem. It looks like this could be true! Take a look at the top-3 C++20 big features and how many developers plan to adopt them soon: 48% for Modules, 46% for Concepts, and 33% for Coroutines.

Andreas:
Modules tops the charts as expected. With C++ build times constantly getting worse, it will be very interesting to see how people use modules to push back against this trend.

It is interesting that in game development, Concepts are ahead of the other features in terms of plans to adopt them with 53%. Of course, these developers are still waiting for the reflection mechanism that is not yet available natively in the C++ language.

Later this year, the C++ Standard Committee plans to make C++23 “feature complete”. However, it now seems it will be a bug-fix release (even though many of the upcoming improvements are very useful), which totally makes sense after such a huge update.

Looking at the C++ standards migration charts from the report, it’s interesting to see how the share of those who don’t plan to update drops between “from C++11” and “from C++14” transition paths:
Migration from C++11 Migration from C++14

Andreas (on some of the transition paths):
From C++98/03: While this looks promising, I wish more teams would take the opportunity to make a greater leap than just going to C++11, which is already a decade old at this point.
From C++11: It’s great to see that so many are looking to skip over C++14 and go directly to C++17 or C++20.
From C++17: It makes sense that lots of people who were already on C++17 are eager to adopt C++20.

Let’s talk about the code quality

To improve code quality and catch potential issues in the early stages, static code analysis tools are very useful. There are many of them, and we can see a lot of activity in this part of the C++ market. The Clang ecosystem is growing blazingly fast, with many tools based on LLVM as a back-end. It is no real surprise that Clang-based tools are trending in the list of tools for Code Analysis and guideline enforcements:
Code analysis tools
Andreas:
It’s also good to see that people are using static analysis tools. Even if you don’t have the budget for paid tools, the free tools like Clang-tidy and Clang-analyzer are great.

Still, the majority of C++ developers prefer tools bundled into their IDEs. We are seeing many code analysis tools providing plugins for the major C++ IDEs on the market. For example, in the recent edition of C++ Annotated we talked about new 3rd party plugins for Code Analysis for CLion – SonarLint and PVS-Studio.

The second most popular response to the question of what code analysis tools do you use was “None”.

Andreas:
The “30% None” crowd needs to wake up and try some static analysis. I guarantee they will find real bugs!
At first, you would think these people use no code analysis at all. So did we! However, while preparing my talk “Code Analysis++” for C++Now 2021, I realized that some of these developers rely on code analysis on CI, like SonarQube. After a few confirmations from the C++ community members, we plan to update the list of possible answers next year to cover this case and, hopefully, decrease the share of “None” answers to this question. By the way, at JetBrains, we are also working on providing the code analyzers from our IDEs as CI services. For that, we’ve recently started the Qodana Early Preview. We hope C++ linters from CLion will soon become a part of it too!

Is there a standard build system for C++?

That’s a very good question. We tend to say there isn’t, and instead we have many options, like Makefiles, Autotools, CMake, Visual Studio, Bazel, Meson, Scons, and many others. What are your thoughts here?
Bryce Adelstein Lelbach, the chair of Standard C++ Library Evolution group, in his talk “What Belongs In The C++ Standard Library?” at C++Now earlier this year, stated that we actually have one! It’s CMake. If you still have concerns here, just look at how it has grown over the years (let’s compare the top-3 most popular build systems in C++ through the last 5 years):
Build systems in C++

There are many open source projects that tended to use Makefile in the past, but are moving to CMake these days.

What about other C++ tools?

For unit testing, Google Test is trending, the same as in previous years. But we agree with Matt:
It is still disappointing to see a third of developers not writing any unit tests at all.

Dependency management is one of the major pain points for C++ developers. We still mostly build libraries as part of our projects, which is not an easy task given the variety of possible build systems in the C++ world.
Dependencies in C++
Matt:
Nearly three quarters of respondents lack a good packaging solution. Having to build libraries separately, prebuild, or use system package management means either developer labor or reliance on external parties to build them. That can mean getting behind on new versions, and adds complexity to upgrading or changing compilers.

Andreas:
It wouldn’t be C++ if we didn’t have many competing solutions to this problem, but I can’t help but wonder if we’d all be better off if we just picked one and went with it.

We’d love to know what you think about dependency management in C++? Do you use Conan, Nuget, or vcpkg? Leave us a comment below.

While we are still on the topic of tools, we are pleased to see that CLion is in the top-3. We have big plans to improve and evolve CLion in various directions. We keep an eye on the current trends in the C++ ecosystem and make sure there is support in CLion for our users to utilize them.

Andreas:
Quite impressive numbers from CLion considering it’s such a young IDE. I can see why though, having recently switched to it myself!
If you are working on a non-commercial open source project, don’t forget you qualify for a free license for our IDEs!

Comparing to C++ Foundation Lite Survey 2021

Validating Developer Ecosystem results against other community surveys and research is important and helps make us confident in the results. Even when the results are different, it’s not always a bug, but often it is down to different methodology. Understanding these differences help us understand the trends correctly. For C++, we validate our results against C++ Foundation Lite Survey results.

This year, there are 2276 responses in the Developer Ecosystem survey and 1873 in the C++ Foundation survey. We spotted a few major differences in the data origins:

  1. Experience: The majority of the C++ Foundation Lite survey respondents have 10+ and even 20+ years of programming experience. For Developer Ecosystem research (C++ audience) more than a half of the respondents have 1-5 years of experience.
  2. Geography: We are also geographically different, as the top-3 countries in C++ Foundation results are the United States, Germany, and Russia, while in the Developer Ecosystem (C++ part) it’s China, India, and the United States. This bias is likely because the C++ Foundation Lite survey is only provided in English, while the Developer Ecosystem survey is localized into 9 additional languages.
  3. Specialization: Gaming is trending in the areas of development in C++ Foundation Lite results this year (they got 31%). That’s why the results are often shifted towards the Microsoft ecosystem and tools (which is a default for many developers in this area).

You can learn more about Developer Ecosystem methodology in the corresponding section of the report.

To compare, we apply the same methodology and selection process to the raw data of both surveys. In the resulting groups similar trends are observed, but some differences are still present:

  • While the top-3 project models are the same, Ninja and Qmake are twice as popular among C++ Foundation Lite survey respondents.
  • Developer Ecosystem respondents tend to use more programming languages besides C++. Java, JavaScript, SQL, PHP, Swift, and Kotlin are much more popular among them, whereas C++ Foundation Lite survey respondents use Assembly, Objective-C, and Haskell more actively.

That’s it! Check out the full report and let us know which trends you find the most interesting and exciting, and which are a little disappointing to you.

CHECK THE FULL REPORT

The JetBrains C++ team
The Drive to Develop

CLion 2021.2 Release Candidate

$
0
0

We are approaching the release, and the CLion 2021.2 Release Candidate is now available for download!

To install CLion 2021.2 RC (build 212.4746.61), download it from the website, update from our Toolbox App, or use this snap package (for Ubuntu).

CLion RC

You need to have an active subscription or a trial license to use CLion 2021.2 RC. No patches will be provided for this release candidate, but you can expect a patch that will update the latest 2021.1 build to the 2021.2 release version.

Give the RC build a try, and make sure to report any problems you find to our issue tracker. We’ll do our best to sort out any pressing issues before the final release, though in some cases the fixes might be postponed until the 2021.2.x bug-fix updates.

DOWNLOAD CLION 2021.2 RC

The highlights:

  • CLion supports Makefile and GNU Autotools projects, and we are continuing to improve the make command output parser so that it handles such projects even more accurately. In this RC build we’ve fixed an issue with the yasm/nasm invocations (CPP-21708) and improved the preconfiguration step settings (CPP-25744).
  • We’ve fixed a performance issue affecting code highlighting (CPP-25376) and the incorrect syntax highlighting for integer literals with a leading zero followed by a single quote (CPP-25429).
  • A false notification about the CTest version has been removed (CPP-25827).

The full release notes are available here.

Your CLion team
JetBrains
The Drive to Develop

CLion 2021.2: CMake Presets, GNU Autotools Projects, Debugger Updates, New Static Analysis, and More

$
0
0

The C++ ecosystem is evolving, and so too is our cross-platform C/C++ IDE. CLion 2021.2 can help you by protecting your code from typical C++ memory safety issues, simplifying your build configurations, and making debugging easier and more effective.

CLion 2021.2 release

To update to the new version, you can use the Toolbox App or a snap package (on Ubuntu), download the installer from our website, or apply the patch update to upgrade from the lastest 2021.1 build.

DOWNLOAD CLION 2021.2

In this release:

Build system updates: CMake, Makefile, GNU Autotools

As we see in the Developer Ecosystem research, the three most popular build systems in C++ have remained unchanged:
Build Systems
CLion can work with 2 of them – CMake and Makefile. msbuild is natively supported in Visual Studio, while C++ support can be enhanced with the ReSharper C++ extension. CLion 2021.2 brings significant improvements to CMake and Makefile support. Let’s check out the details!

CMake

Since the early days of CLion, CMake has been the IDE’s primary project model. In 2021.2, this support has had a massive update in order to keep it aligned with the ongoing CMake evolution.

CLion 2021.2 bundled CMake 3.20 and supports one of the biggest features of this CMake release – CMake Presets. This feature addresses the common need to share the CMake build configuration settings with other people.

If you open a project with CMake Preset files (CMakePresets.json, CMakeUserPresets.json, or both) in CLion 2021.2, the IDE will automatically load the build presets and store all of their settings in CLion’s CMake Profiles. Presets that are loaded in CLion are read-only, but you can still edit .json files in the CLion editor. When you edit a .json file or update the preset externally, you will get a notification with the option to reload the changes.

CMake Presets

This now works for version 2 presets and build presets.

If you want to learn more and see CMake Presets support in action, watch this video:

A few more important CMake enhancements in v2021.2:

  • New CMake project templates for C and C++ executable, CUDA, and Qt projects were added and are configurable in Settings/Preferences | Editor | File and Code Templates.
  • CMake targets can now be specified as Before Launch tasks in the Run/Debug configuration. With this, you can execute a built-in or user-specified CMake target before launching the configuration in CLion.

Makefile and GNU Autotools

In previous versions we introduced Makefile project support in CLion. However, it had a significant limitation – Makefile files should be present in the project root directory to load the project automatically. Many projects that use make rely on pre-configuration steps which in turn generate a Makefile file for the project. CLion 2021.2 supports such projects now too!

The exact command executed by CLion for pre-configuring the project can be tuned in Settings/Preferences | Build, Execution, Deployment | Makefile:
Preconfiguration step

Adding automatic support for the pre-configure step made it possible to load GNU Autotools, Kbuild, and PERL MakeMaker projects in CLion. Check out all the details in the corresponding blog post. Here is the list of projects we test our Makefile projects support on.

Debugger enhancements

We have continued to work hard on improving CLion’s debugger. The CLion 2021.2 update brings better Natvis support and minidumps for Windows users, and updates to breakpoints and remote LLDB. Let’s briefly go through these enhancements.

Easier debugger configuration

It’s easy when everything is compiled and debugged locally inside your IDE, but there are many more complicated setups where you need to debug your code. In this release, we worked on improving the configuration experience.

When you debug an executable built somewhere else, the path mappings might be too complex to fill them in in the debug configuration, but the debugger relies on a full file path when stepping through the code. It’s now possible to use just the file name for breakpoints in such cases. These breakpoints are called Relaxed breakpoints.
Relaxed breakpoints

Another case is when you debug a custom executable using a fake project or when there is a library built on CI without the source code being in the project. Stepping to these source locations will cause the disassembly view in CLion, as the IDE can’t locate the actual source code. Now you can explicitly specify where to find the source files. The notification is shown in the disassembly view.

Regarding the disassembly view, there is now the ability to set breakpoints there. For these address breakpoints, you can configure many useful behavior patterns like the condition when it should be hit, and if it should suspend the execution or just log a message:
Address breakpoint settings

Preview Tab in debugger

When stepping in the debugger, having many tabs with new files opened in the editor can clutter it up. To keep your editor clear, you can view files in a single tab, rather than opening each file in a new one. Just enable Preview Tab.
Preview Tab in debugger
Enabling Preview Tab affects more than just the debugger behavior – it’s an IDE-wide feature affecting the way files are opened in the editor. Check out the documentation if you want to learn more.

Debugger on Windows

On Windows, if you use the Microsoft Visual C++ compiler toolchain, the debugger from Visual Studio is not allowed in CLion due to licensing restrictions. That’s why CLion provides its own LLDB-based debugger. The same debugger is also used in Rider for Unreal Engine Preview, and unsurprisingly it has evolved quickly, thanks to the huge amount of feedback we get on it from the users.

In CLion 2021.2, this LLDB-based debugger gets a massive overhaul to achieve better data rendering. The change affects both built-in rendering and Natvis support. For example, CLion now automatically generates colored one-line summaries for all structures not covered by Natvis, shows the [Raw View] for Natvis-generated values, and more. You can check all the details here.
Natvis rendering

Windows users can now debug with core dumps. The same Run | Open Core Dump action as previously on Linux and macOS helps start debugging sessions on Windows. Finally, it’s now possible to switch to the cmd.exe console to run and debug applications instead of using the internal CLion console.

LLDB

In CLion, you can debug any arbitrary executable remotely. This is now possible with both GDB and LLDB. We renamed the GDB Remote Debug configuration to Remote Debug and made it serve both LLDB and GDB remote debug cases:
Remote debug with LLDB
On a remote host, you’ll need to launch lldb-server/debugserver. Check out our web help for more details.

To improve debugging with LLDB, LLDB v12.0 is now bundled in CLion 2021.2.

FreeRTOS thread view

FreeRTOS is a real-time operating system for microcontrollers. To debug applications using FreeRTOS, CLion provides a view of FreeRTOS tasks (threads) with their names and current statuses in the debug tool window:
FreeRTOS
To get the FreeRTOS thread view, turn it on in Settings/Preferences | Build, Execution, Deployment | Embedded Development | RTOS Integration. Learn more in our online documentation.

Cling interpreter

When studying C++ or prototyping something new, you might want a playground to check out your ideas, as in other languages. The Cling interpreter can help you with this! All you need to do to start using it is just download the Cling executable for your platform or install it via your OS-specific dependency manager, and configure a path to it in Settings/Preferences | Languages & Frameworks | C/C++ | Cling.

The IDE integration provides you with an IDE action to start the Cling session and a set of code intentions that allow you to send the current line or selection to Cling:
Cling intention
Of course, you can simply type code directly in the Cling terminal:
Cling session in CLion

Object lifetimes static analysis

According to the C++ Foundation Developer Survey, memory safety issues like use-after-free/delete are among the top points of frustration for C++ developers. Many thanks to Herb Sutter for his Lifetime safety proposal that is trying to address these issues in C++.

The proposal is not yet in the C++ standard, and major C++ compilers are not adopting it actively currently. But you don’t have to worry – CLion’s built-in static analyzer can check object lifetimes for you now!

CLion catches common cases of dangling pointers and escaping from a local scope:
Value out of scope inspection

Additionally, mark your code with GSL annotations and help CLion catch even more potential Lifetimes issues:
GSL annotations

Profiling in remote mode and on WSL

Eliminate performance issues in your code by using profiler integration in CLion. With the CLion 2021.2 release, profiling is now possible in remote mode and on WSL! To do so, configure the path to the Perf tool in CLion Settings/Preferences | Build, Execution, Deployment | Dynamic Analysis Tools | Perf.

While we are on the WSL topic, CLion now supports WSL whether it’s installed from the Microsoft Store or a custom distribution. All WSL distributions returned by the wsl -l -v command should now be listed in the WSL drop-down list in Settings | Build, Execution, Deployment | Toolchains.

Version Control and Local History

To make sure your commit is good enough, you can analyze the code with the customized profile or even run the selected test configuration before actually committing the code:
Before commit actions

If the test fails, you can review the details and rerun the commit checks after the necessary fixes:
Running tests before commit

What if your project is not under the version control? Local History can help save you from accidental changes! You can now search through file revisions. This is useful if you need to look for something you’ve accidentally removed and revert the change:
Local History Search

Plugins update

Starting from this release, you can use CLion with a localized UI in Chinese, Korean, and Japanese. Install the non-bundled language pack plugins in Settings/Preferences | Plugins.

For Rust users, IntelliJ Rust introduced a new name resolution engine and initial WSL support. The plugin is now also capable of expanding certain procedural macros. We’ll publish a separate blog post about these changes later.

Other changes

Finally, we want to briefly mention some other valuable enhancements:

  • Postfix code completion in C++ now works for literals.
  • If you want certain operations to be performed on Save, you can now configure them all in one place in Settings/Preferences | Tools | Actions on Save.
  • When using remote development mode for developing in Docker, you can use the “Local or mounted folder” connection type to avoid unnecessary source synchronization.
  • You can now configure the colors that are used in Doxygen comments in Settings/Preferences | Editor | Color Scheme | C/C++ | Comments | Doxygen.

That’s it for now – we’ll publish a roadmap for CLion 2021.3 soon! Some features, such as custom compiler support and more debugger variables render enhancements, that we planned for the 2021.2 release cycle were moved to the next release, even though we started them during this iteration. This was done as we want to guarantee the best quality of the changes we deliver. Stay tuned!

We encourage you to give CLion 2021.2 a try. Update today if you have an active subscription, or start your free 30-day trial to evaluate the new features!

DOWNLOAD CLION 2021.2

Your CLion team
JetBrains
The Drive to Develop

C++ Annotated: July 2021

$
0
0

Welcome to the July edition of C++ Annotated and its companion, the No Diagnostic Required show!

If you are already subscribed, feel free to skip to the news. If you are new, you can explore all the formats we offer. Choose to read, listen, or watch our essential digest of this month’s C++ news:

  • Read the monthly digest on our blog (use the form on the right to subscribe to the whole blog).
  • Subscribe to C++ Annotated emails by filling out this form.
  • Watch the No Diagnostic Required show on YouTube. To be notified of new episodes, follow us on Twitter.
  • Listen to our podcast – just search for “No Diagnostic Required” in your favorite podcast player (see the list of supported players).

July news

Watch the July episode of No Diagnostic Required below, or keep reading for all the latest news!

Language news

P2300: std::execution

Executors have had a long history in the standardization pipeline – from the first executors paper back in 2012, through several alternate branches, a unification in 2016, and 14 revisions of that paper alone – all building on or reacting to earlier language features like std::future and std::async. And now we have another new paper.

Except this is not an executors paper. While this new proposal, authored by many of the same people, aims to replace the unified executors proposal and cover most of the same ground, it does so using a sender/receiver model instead of executors. Along the way it addresses most, if not all, of the issues with the previous proposal raised by SG1, and it drops some things that were considered unwanted or unnecessary for an initial design. That doesn’t mean it’s smaller, though. It weighs in at over 22 thousand words, vs 15.5 thousand for P0443R14.

I’m not familiar enough with the details to be able to comment on any of this. All I can say is that a design in this space is critical, both for the evolution of the language and its libraries, but also for making full use of our modern multi-core and increasingly heterogeneous computing world. It’s been 16 years since Herb Sutter declared that “The Free Lunch Is Over”. It’s about time we paid for that lunch before someone else eats it all.

P2388: Abort-only contract support

Since contracts were (in)famously removed from C++20, after initially being merged into the working paper, SG21 was formed and has been working to establish a consensus on as much of the groundwork as possible. We’ve commented on some of this work before. We’re now seeing design proposals coming out of that (first was P2182, a precursor to this one). Billed as an MVP, P2388 contains just three almost-attributes and two modes.

The attributes-that-aren’t-attributes (slightly different syntax, for reasons given in the paper) are the minimal form of what was in P0542R5: pre, post, and assert. They simply take predicates to check, with no assertion modes.

The two modes are Ignore (parsed for validity, but generating no code – or time-travelling UB) and Check_and_abort (which does what it says on the tin). No continuation modes. No throwing violation handlers or even custom violation handlers.

The defining limitation of this proposal is the “abort-only” part (hence its presence in the title). Continuation or exception throwing approaches were central to previous disagreements (although there were other issues), so the all-or-nothing approach of this paper, while limiting, is aimed at getting us something, hopefully in time for C++23, which can be built on, possibly even within the C++23 timeframe (although that’s looking less likely).

P2392: Pattern Matching using is and as

Another big feature we had hoped to see for C++23, but which has been looking less likely, is Pattern Matching (P1371). The proposal, which is actually a unification of proposals led by Michael Park and David Sankel, has been ticking along nicely for a few years now, though it has perhaps slowed a bit during the pandemic. Now we have an entirely new paper from Herb Sutter! Is that going to set us back even more?

Well, Herb’s paper, while complete in itself, builds on P1371, but with an important change in direction. Herb recognized, correctly, that the underlying facilities of pattern matching are not limited to inspect statements (or event inspect expressions), which is the new keyword for introducing a pattern match with multiple alternatives. Therefore it would be a shame if we special-cased the syntax just for use in that context. In particular he identifies if statements (and other conditionals), structured bindings, casts, and even requires clauses. Additionally, one of the frequent sticking points of the existing proposal is determining how to distinguish between identifiers that introduce new names (name bindings) and references to existing variables. From a controversial start, using a ^ prefix, to alternately trying case for references or let for bindings, this issue never seems fully settled. Herb sidesteps this by separating the part of the syntax that does one from the part that does the other, and in a way that makes it obvious which is which.

He does all this with just two keywords, perhaps not surprisingly, given the title: is and as. These are more general and more powerful than they might first appear, especially if you’re familiar with similar keywords from languages like C#. Unlike in those languages, these are not just synonyms for applications of dynamic_cast (although they do subsume those in a nice way). They are overloadable operators that, even before overloading, have well defined (if a little complicated to enumerate) semantics that make sense of a whole range of things you can do with them, fairly intuitively. In a pattern match they solve the binding problem by having the introduced names on the left, and references to names and values in a pattern on the right.

But they can be used outside of inspect statements, too. For example, testing whether a variant holds an int could be written as:

if( v is int ) { /* … */ }

Which is much nicer and easier to read than
if( std::holds_alternative<int>(v) ) { /* … */ }

In some cases Herb’s syntax is shorter, but in general it tends to be slightly more verbose, introducing inspect alternates with is and splitting the binding and matching patterns with as. If that’s the cost of being able to generalize through the language, then that might be a price worth paying. But perhaps we can still do both? It will be interesting to see how this goes. It’s not clear whether this will slow us down from getting something into C++23, if that’s even possible at this point. But I think it’s worth exploring.

P2409: Requirements for Usage of C++ Modules at Bloomberg

We have modules in C++20, and before they were adopted there was plenty of discussion about the potential for problems with tooling around them that was resolved to most parties’ satisfaction. So what is this paper all about?

Well, part of that resolution was a proposal for the Tooling study group (SG15) to produce a C++ Ecosystem Technical Report on modules (P1688). This new Bloomberg paper also proposes a TR. At first I was confused by this, so I contacted the author who confirmed that this is a different TR, much more focused on the set of requirements laid out in the paper. Despite the name, the requirements are not really specific to Bloomberg, but potentially common to many projects with inter-dependencies which are not using a mono-repo. Most of the requirements are about module discoverability; in fact, three of them start with the words, “Module discoverability should…”, and three others have the word “discover” or “discoverable” in them. The remaining of the seven requirements is about testing for the existence of a module.

So it’s good to see SG15 still moving forward with recommendations for how modules should be used in real-world cases and how the tooling around them will need to account for that. Whether this TR, the original one, or some combination ends up getting out, we’re inching ever closer to a modules world.

The C++ ecosystem in 2021

This month we finally published the Developer Ecosystem 2021 report with infographics based on the survey data we collected during the first months of 2021. There are many interesting observations for C++, which we discussed in this blog post with Matt Godbolt, creator of Compiler Explorer, and Andreas Kling, creator of SerenityOS.

Nearly 1 out of every 5 C++ developers is already using C++20, even though major compilers have been very slow to adopt this big C++ release. 48% plan to start using Modules in the next 12 months. Concepts are close behind, and are a choice for 46%.

We still see a third of developers not writing any unit tests at all, and I agree with Matt that this looks disappointing. Many competing solutions are present for the package management problem. But manually bringing the library source code into the project is still trending for 26% of the respondents.

The top three project models are still CMake, Makefile, and Visual Studio, but the last two have swapped spots.

Check out the full report and the accompanying blog post for other interesting facts.

Be Wise, Sanitize – Keeping Your C++ Code Free From Bugs

If you are still not using sanitizers, this might be a good article to get started with. It describes Address Sanitizer (ASan), Memory Sanitizer (MSan), and Undefined Behavior Sanitizer (UBSan), with short explanations of how they all work and what issues they are capable of catching. The article also provides estimates of the CPU and memory overhead.

For ASan, there’s a nice visualization of so-called red zones around each set of bytes allocated with the malloc function. These red zones are added by a run-time library and help detect use-after-free, double-free, buffer overflows, underflows, and other issues.

For MSan, you may want to read this Google paper to understand the algorithm in detail. MSan helps detect the use of uninitialized memory. The approach uses bit-to-bit shadow mapping to avoid false positive reports on the copying of uninitialized memory. All newly allocated memory is “poisoned”, that is, corresponding shadow memory is filled with 0xFF, signifying that all bits of this memory are uninitialized. Warnings are raised when uninitialized memory is incorrectly accessed.

For UBSan, you can learn about the flags for many specific UB cases that the sanitizer can catch, like integer-divide-by-zero, signed-integer-overflow, and others (the flag names speak for themselves).

There are still some downsides for using the sanitizers discussed in the article, but it’s to know about your options.

C++20’s concepts are structural. What, why, and how to change it?

C++20’s concepts are now considered one of the major benefits of the new language standard, and there are many guidelines promoting Concepts. Jonathan Müller wrote a blog post comparing nominal and structural concepts. The most interesting outcome is that, “if you want to distinguish between identical syntax with different semantics, you need to introduce some syntax to distinguish it.”

In the case of structural typing, a type models the concept if it has the same structure as the one required by the concept. This also means that naming becomes really important – names and structure are taken into account, not the semantics. The problem is illustrated by the example with the TShirt class from the article, which passes the semantic checks for std::vector. To avoid such situations, techniques like a dummy typedef or inheriting from a tag type are used.

In other languages in which Concepts were introduced at the very beginning, a developer has to state the concept explicitly to model it. Well, that doesn’t help with 30-year-old C++ code bases and many library dependencies that are added manually! Check out the article for many self-explanatory examples.

Counting in Iteration Models

Barry Revzin, who gave a talk about iteration models of several different languages at this year’s C++Now conference, wrote a blog post in which he ungrouped the C++/D and C# models. The actual issue is highlighted in P2406 and is about counted_iterator, which increments its internal iterator even when it reaches its own end. In C# and Rust, access to the underlying enumerator, iterator, and so on is provided based on the count check. In C++ and D, on the contrary, the underlying iterator is incremented even if we decrement count to 0. Let’s see what the committee says about the proposal and which option will be used to address the case.

An iterator IS-NOT-A const_iterator

Arthur O’Dwyer made an interesting discovery about iterators. In the STL, it is guaranteed that C::iterator is convertible to C::const_iterator. This implicit conversion is implemented differently in libc++/libstdc++ and in Microsoft’s STL. The former uses a converting constructor, while the latter uses a base class conversion. That makes a difference when an implicit conversion sequence is used. Arthur also notes that public inheritance should be used only for IS-A relationships. Microsoft’s implementation seems to violate that principle. Check out the blog post for more details.

Performance of the Parallel STL Algorithms

Rainer Grimm wrote a couple of posts recently about the parallel algorithms of the Standard Template Library. In addition to describing the basics about sequential, parallel, and vectorized execution policies, he also measured their performance to examine the benefits. Rainer measured the test with Microsoft Compiler 19.16 on Windows and the GCC 11.1 On Linux. The results were just as expected:

  • On Windows with 8 cores, parallel execution is faster than sequential by a factor of more than 10, while parallel and vectorized execution take comparable time. The latter result is reasonable, as Visual C++ implements the parallel and parallel unsequenced policies the same way.
  • On Linux with 4 cores, parallel execution is faster than sequential execution by a factor of about 4, while parallel and vectorized execution are again comparable.

How to Return Several Values From a Function in C++

In yet another practical article, Jonathan Boccara talks about how to return several values from a function while making sure no redundant extra copies are made, RVO is applied, and the code looks nice and readable. The article is focused on improving these parameters for a solution that returns a bundle, like an std::pair or std::tuple. On the call site, the values are retrieved using structured bindings (C++17) or std::tie (C++11).

Another question is how to avoid the typical errors when returning values of the same type. If you mix up their order, you might never even notice it. To be on the safe side, use a proper naming scheme, or maybe a struct, or even strong types.

Qt Creator 5.0 Beta

Qt announced the Qt Creator 5.0 Beta build, which includes a very interesting change. For some time now, Qt Creator has relied on the libclang-based code model for providing smart features in C and C++. Now it has moved to Clangd. There is a difference between the two approaches. Libclang is a library, so the language model runs inside the actual IDE application. Clangd, on the other hand, is a daemon which communicates with the IDE via the Language Server Protocol.

One more update in this build is Qt’s support for building and running applications in Docker containers. With it you can create a Docker device in the Device settings and set it as a “Build device” and a “Device” in a Kit.

CMake 3.21 is released

While many of us are still adopting CMake 3.20, which brought many cool things like CMake Presets, Kitware released CMake 3.21. This version works with the MSYS runtime environment, adds a generator for Visual Studio 17 2022, and supports the C17 and C23 standards. Another interesting change is that messages printed to the terminal may now be colored by message type. And finally, CMake Presets has reached version 3 in CMake 3.21.

Hot Reload in Visual Studio 2022

A new preview of Visual Studio 2022 provides Hot Reload for .NET and C++. When you are in a constant loop of editing the code, debugging the resulting app, and editing it again, the speed with which your code changes are applied is important. Normally you stop the debugging process, introduce changes, recompile, and launch the debugger back. With Hot Reload, the loop becomes shortened, as new code changes are applied to the application under the debugger without stopping it. This saves you time on restarting the app, building, and waiting for the breakpoint to be hit again. Hot Reload injects the changes into the app dynamically and doesn’t trigger a full rebuild of the app. The feature is available only for MSBuild C++ projects and the Visual Studio debugger at this time.

CLion 2021.2 is out

The CLion 2021.2 release is aligned with the most recent changes in the C++ ecosystem. It adds static analysis to catch object lifetimes issues (meaning you don’t even need to wait for Herb Sutter’s proposal to be implemented in the compilers), and it introduces support for the brand-new CMake Presets feature. This feature from CMake 3.20 simplifies the app build configuration process. To reach feature-parity across many toolchains and setups, profiling is enabled for remote mode and WSL. Plenty of debugger enhancements have been implemented. And finally, for those who are learning the C++ language or prototyping actively, CLion integrates the Cling interpreter. The integration includes not only Cling sessions built into the editor, but also many code intention actions to work with these sessions and send the corresponding code to them.

And finally, Bjarne Stroustrup on the future of programming

Bjarne Stroustrup, the creator of C++, gave an interview to Yegor Bugayenko. The 1-hour-long YouTube video covers many deep and global questions touching on the goals and evolution of programming languages. Bjarne also talks a lot about his vision for C++. Let us share just a few highlights from the insightful video before you go and watch the whole thing:

  • How do you make a language popular? Solve a problem, instead of trying to make a statement. And care about the language in the long term.
  • Why is a language committee needed to add features to a language? Because we need a broader view. We need to listen to everyone, but still follow the original goal and defend it.
  • The NoCode trend and AI for code improvements and refactorings: will these things replace human beings in the future? AI is good at searching for and identifying abnormal behavior, but it’s still local and limited. Someone has to think about the overall structure and architecture. Also, with automated refactorings, strong guarantees are required. We need to verify that the performance criteria is taken into account and also prove that the code is actually the same after refactoring.
  • Is it important to design simpler languages that are still powerful? The solution is not necessarily in the language. The answer for C++ is the C++ Core Guidelines, which can guide you in writing good C++ code. So it’s guidelines, plus a minimum set of libraries to support that, plus static code analysis to enforce the guidelines.

About the authors

Anastasia Kazakova Anastasia Kazakova (@anastasiak2512)
As a C/C++ software developer in Telecom and Embedded systems, Anastasia was involved in research estimating the broadband capacity of home networks and participated in launching 4G networks. She is now the Product Marketing Manager for JetBrains C++ tools.
Phil Nash Phil Nash (@phil_nash)
Phil is the original author of the C++ test framework Catch2. As Developer Advocate at SonarSource he’s involved with SonarQube, SonarLint, and SonarCloud, particularly in the context of C++. He’s also the organizer of C++ London and C++ on Sea, as well as co-host and producer of the cpp.chat podcast. More generally, Phil is an advocate for good testing practices, TDD, and using the type system and functional techniques to reduce complexity and increase correctness. He’s previously worked in Finance and Mobile and offers training and coaching in TDD for C++.

What Is Our Focus for CLion 2021.3?

$
0
0

With CLion v2021.2 being recently released, we are now collecting feedback and working on the most important bug-fixes. It’s also time to start the new development cycle, so let’s see what we will be busy with in the next 3–4 months.

Special thanks

Before we talk about the plans, we’d like to first thank all of the participants of our recently finished Early Access Program! We are very grateful for every piece of your feedback, as it helps us polish and fine-tune the final release in many environments. As a special thank you to the most active EAPers, we’ll send them a special JetBrains gift box! Congratulations to:

  • Eyal Amir
  • Clare Macrae
  • Jiawen Geng
  • Roland Illig

We’ll email you in the next few days regarding your postal address and some other details for delivery.

Roadmap for CLion 2021.3

IDE performance and responsiveness is our major priority. To improve them, we keep inspecting user snapshots and thread dumps, as well as testing CLion on various projects on our side. There are many new ideas and approaches we keep experimenting with in our roadmap, and we’ll deliver when we are sure that these experiments bring significant value to our users.

The following is only a preliminary plan, as some tasks will be started but may not be finalized until after the actual release, or might be changed or rescheduled for various reasons. We cannot guarantee that all of the features listed below will be included in CLion 2021.3.

Talking about more specific directions for the upcoming release, we’d like to highlight the following activities:

  • Toolchains
    • Bundle MinGW toolchain in CLion installer on Windows (CPP-25680).
    • Add the ability to configure the toolchain environment via script (CPP-11768).
  • Project models
    • Bundle Ninja and use it as a default generator for CMake projects.
    • Continue with CMake Presets support, and maybe add support for CMake Presets version 3 (CPP-26183).
    • Fixes for Makefile projects and pre-configuration steps.
    • Automatically find executables corresponding to Makefile build targets (CPP-20678).
  • Debugger
  • Embedded
  • Static analysis
    • Improve global DFA and Lifetimes analysis, cover more cases, and make it even more accurate.
  • Annoying problems
    • Address the most annoying cases when automatic include directives are added inaccurately (CPP-5501).

Apart from this list, there are a few other experimental features we are working on. But since they are unlikely to be delivered in 2021.3, we’ll talk about them later.

If you have any new feature requests, please send them to our tracker. We’re listening!

Your CLion Team
JetBrains
The Drive to Develop

CLion 2021.2.1 Bug-fix Update

$
0
0

CLion 2021.2 was released just a few weeks ago, and you can find out what’s new in this blog post or on the website. With many debugger enhancements, support for the brand-new CMake Presets, integration with the Cling interpreter, and Lifetimes analysis working as you type your code, this release significantly improves the user experience.

We are now happy to announce that the CLion 2021.2.1 bug-fix update is out! It addresses several problems we didn’t finalize for the original release. The 212.5080.54 build is now available on our website, via the patch update, in the Toolbox App, or as a snap (for Ubuntu).

DOWNLOAD CLION

The highlights include:

  • Project model
    • The “Mark directory as excluded” action is now back in the context menu. We apologize for this regression.
    • Compiler information is now collected correctly when duplicating flags are used (CPP-25608), and also for the IAR STM8 compiler (CPP-25996).
    • We’ve fixed CMake Presets parsing when the environment variable has an env macro (CPP-25920).
  • In the debugger, several issues with visualization have been fixed for the LLDB-based debugger on Windows (for the MSVC toolchain).
  • Template parameters are no longer folded by default. If you want default folding back, enable Preferences/Settings | Editor | General | Code Folding | Fold by default | C | Template parameters.
  • Formatter
    • We’ve fixed an editor freeze caused by ClangFormat (CPP-25091).
    • The broken auto formatting of switch statements with return has been fixed (CPP-26011).
    • New options were added: Preferences/Settings | Editor | Code Style | C/C++ | Spaces | Before/After ‘for’ colon/semicolon. They control the number of spaces before/after colons and semicolons in range-based for and for loops.

You can find the full release notes here. If you haven’t yet updated to v2021.2, now is a great time to do so!

If you’re wondering what’s coming next, please check out the roadmap for 2021.3.

DOWNLOAD CLION

Your CLion team
JetBrains
The Drive to Develop

C++ Annotated August 2021: Practical Modules, C++20 Attribute to Help with EBO, Valgrind, Intel Compiler, and CLion News

$
0
0

Our monthly C++ Annotated digest and its companion, the No Diagnostic Required show, released a new episode with August news!
If you have already subscribed, feel free to skip to the news. If you are new, you can explore all the formats we offer. Choose to read, listen, or watch our essential digest of this month’s C++ news:

  • Read the monthly digest on our blog (use the form on the right to subscribe to the whole blog).
  • Subscribe to C++ Annotated emails by filling out this form.
  • Watch the No Diagnostic Required show on YouTube. To be notified of new episodes, follow us on Twitter.
  • Listen to our podcast – just search for “No Diagnostic Required” in your favorite podcast player (see the list of supported players).

August news

Watch the August episode of No Diagnostic Required below, or keep reading for all the latest news!

Language News

D2422R0 “Remove nodiscard annotations from the standard library specification”

This is another example of a paper that has recently been covered on CppCast, it appears to be an unusual paper at first glance. That was certainly my reaction when I first heard it discussed on CppCast, and that seemed to be Rob and Jason’s reaction, too.

It’s worth digging into this a bit more to find out what’s really being said in this paper. It’s definitely a case where the devil is in the details and a little more background is insightful, so let’s dive in.

[[nodiscard]] is an attribute introduced in C++17 as a hint that compilers or other tools can choose to check whether the return value is used or explicitly cast to void by the caller. It can be applied to a function (including member functions), in which case it refers to the return value of that function or to a type (including enums), in which case it applies to any function that returns values of that type – great for error codes or types. In C++20 it was extended to allow a message to be included that explains why the value should not be discarded.

Along with error types, functions that have no side-effects (are “pure”) also seem like good use cases. Back in May, we talked about a proposal for adding [[nodiscard]] to the iterators library for this reason. There have been other proposals, many already accepted into the working draft for C++23, that add it to other functions, like memory allocation functions and empty() member functions.

These all seem like great uses of [[nodiscard]] – almost no-brainers, even (although there were some less obvious cases).

So what’s the problem? Rewind to where we said these should be considered “hints”. This is a definite case of “no diagnostic required”. On the other hand, standard library authors are entirely free to add [[nodiscard]] anywhere they see fit, and many have done so. Microsoft’s stdlib contains over 400 such annotations, for example. Beyond that, even without [[nodiscard]], tools (including compilers) are allowed to issue warnings when return values are discarded if they think there is a good case for doing so.

So that raises the question: should something that doesn’t specify anything be put into a specification? The only possible change is that some additional warnings may be issued. Useful warnings, for sure (assuming they’re not false positives), but at what cost?

The downsides include:

  1. Committee time. This is not as trivial as it sounds. The committee is already overstretched and these proposals take more time to review and process than you might think. If the goal is to get to 100% coverage on functions/types that should be annotated it may be worth the hit – at least at some point – but, as we’ll see, that may not be an appropriate goal.
  2. The danger of false positives and other unintended side-effects or bugs. The best way to minimize these is to learn from implementation experience. That can be put into motion now, by proposing patches to stdlib implementations to add [[nodiscard]] in the appropriate places. Then we wait.
  3. A partial job, especially as coverage gets higher, raises questions about those places that have not received the annotation. Does it mean they have side effects? Is the return value unimportant?
  4. Verbosity. All these annotations add up, especially when added alongside const, constexpr, noexpect, and so on. There’s a can of worms here, but an important one, which we’ll come back to.

To sum up so far, D2422 is not proposing that we don’t want warnings for misuse of these functions and types. Rather it is saying that specifying them in the standard is not the best or most practical way to do so, so let’s slow down and reconsider. At the very least, let’s implement them directly in the major stdlibs, see how it shakes out, then eventually standardize the existing practice.

There may also be better ways that are being discussed within the committee, but for which there are no papers written yet. It’s too early to say what will come of these, but it seems important not to run in the opposite direction just yet. One of these ideas is: specifying (possibly in a separate document) en masse categories of functions for which [[nodiscard]]-like behavior in the tooling may be applied (e.g. all empty() methods) rather than specifying that they each have the [[nodiscard]] attribute. Another possibility is something like a [[discardable]] attribute that we could start applying in cases where we know we want that ability. Then, existing compiler flags such as -Wunused become more useful due to less noise, but remain an opt-in option. There are also references to a proposal to add a [[pure]] attribute. These are all ideas and opinions in the mix, but the underlying thought is that annotating [[nodiscard]] everywhere is not a practical approach, and therefore spending committee time on doing so is inefficient at best and self-limiting at worst!

P2372r2 “Fixing locale handling in chrono formatters”,
P2419r0 “Clarify handling of encodings in localized formatting of chrono types”

After talking so much about one proposal (which itself is talking about the removal of proposals already adopted), let’s talk a bit about these couple of papers that, on the surface, relate to how std::format works with std::chrono. In fact these are really about text encoding. We’ve talked many times about std::format and at least once about std::chrono, but not enough about text encoding. It’s a really tricky, deep subject that is often overlooked, especially by application developers who very often like to pretend that it doesn’t exist at all! This is not helped by the standard library traditionally brushing all the handling under the locales carpet. The string classes (even std::wstring) say nothing at all about encodings. There’s a lot of ongoing, largely unsung, work being done by SG16 (the Unicode Study Group) to bring stronger, fuller Unicode support to C++. Some of that work has been bearing fruit in the current standards, but the biggest payoffs are quite a way off yet. In the meantime, let’s at least try to remember that using UTF-8 doesn’t mean we don’t have to worry about text encodings.

P2388R1 “Minimum Contract Support: either Ignore or Check_and_abort”

Last month we looked at R0 of this paper, which at the time was called “Abort-only contract support”. It’s not just the name that has changed, though. The paper has been substantially re-organized and expanded, with most review actions addressed and wording added. There is a joke within the committee that it’s easy to encourage paper authors to explore “further work in this direction”, but in this case, I see this as a sign that things are actively moving along and this is being taken seriously. Maybe some form of Contracts support is on track for C++23, after all?

Now, back to standards that can be used today…

Empty Base Class Optimisation, no_unique_address and unique_ptr

If you haven’t heard about this new C++20 attribute – [[no_unique_address]] – you definitely should check the article by Bartlomiej Filipek. He talks about Empty Base Class Optimization first, which allows saving memory on empty structs via inheritance. The idea is that if you know that your class is empty, then you can inherit from that class, and the compiler won’t enlarge your derived class.
However, C++20 brought an easier way to achieve a similar effect. A new attribute indicates that a unique address is not required for a non-static data member of a class. Interestingly, ABI might be affected as the usage of the [[no_unique_address]] attribute changes the struct layout. This situation is discussed in the GitHub issue for Microsoft STL. It was noticed there that Clang listed this attribute as supported in v.9, but not when targeting Windows. And while Stephan T. Lavavej stated that the attribute is now supported in MSVC, it’s too late to request Clang support to take advantage of it before the C++20 ABI lockdown.

Don’t explicitly instantiate std templates

The major outcome of the new article by Arthur O’Dwyer that C++ developers should take as a rule is in the title. With a good set of examples (from simple ones to real-life ones) he explains why it’s bad. The major idea is that implicit instantiation is lazy and can only instantiate the required parts, while explicit instantiation does so for every member. The standard library relies on this laziness a lot, so when you explicitly instantiate std templates you get yourself into trouble.
For Clang users, there is an attribute that is probably not so widely known, which helps protect code from such explicit instantiations and related issues: exclude_from_explicit_instantiation.

C++20 modules with GCC 11

As modules-related topics are so hot now, we’ll discuss a few recent posts dedicated to this long-awaited C++20 feature. Niall Cooling discusses the C++20 modules in his new article, focusing on two different approaches to organizing the module structure – single file modules and separate interface, and implementation files – to manage the structure more easily.
He builds a very basic Hello, World! example using these approaches and GCC 11, providing tips on constructing modules with this compiler specifically. There are some differences from Microsoft’s implementation, so check them out carefully if you have tried modules with MSVC before. Pay special attention to the lack of file name extensions and common agreements.
Niall shows how to build a simple module, export functions, namespaces, and types, import things, and build everything together. Module partitions are left out of the blog post scope and will be discussed at a later date.

Moving a project to C++ named Modules

The Microsoft team has also published a post on new module practices, which you can use as an example-based tutorial on building a named module for the existing code. The original project is published on GitHub, so you can play with it along with reading the article. Interestingly, the project is CMake-based, but to introduce modules you’ll have to switch to msbuild (which can be generated from CMake), as CMake still doesn’t have support for C++20 modules.
The newly created modules mimic the project’s include directories structure, and the modules are created from the corresponding header files. But the most interesting part is dedicated to the modularization of the 3rd part code, and this is where some non-trivial work is required. For example, static constants have to be wrapped with functions to import later. This is because an internal linkage entity can’t be exported.
All the efforts are rewarded in the end with a significant compilation time improvement!

Valgrind

After posting in the craft::cpp blog about sanitizers, Marin Peko did a dive into the Valgrind tool. You might say it’s too old, but it still can work better than sanitizers in a few use cases.. The most obvious one is catching issues in a library whose source code is inaccessible. Sanitizers require recompilation so they capitulate here immediately. While Valgrind works and provides meaningful results, suppression files help tune this result and make it even more useful. Another case is to search for memory errors with address sanitizers and at the same time detect uninitialized memory reads with memory sanitizers. That’s simply not possible with sanitizers, but no such problem exists with Valgrind.

Another interesting observation is that Valgrind can be customized. Its core part loads the software and disassembles it, and the tool plugin adds the instrumentation and assembles it back. This other part can serve different purposes: checking for memory leaks, detecting data races in multi-threaded applications, analyzing the heap memory usage, and so on. Valgrind is actually not a tool, but a family of tools based on the same core.

There are known limitations of the Valgrind approach and they are discussed in the article. For example, the execution times and memory usage are significantly larger than in the sanitizers case. Valgrind also won’t help you catch overflows in stack and global variables. This is because it only has access to the heap allocations performed by the malloc function. Before making a choice between Sanitizers and Valgrind, read through the article to learn the Valgrind basics.

Intel C/C++ compilers complete adoption of LLVM

Big news was announced by Intel – they moved their compiler to the LLVM infrastructure. Intel’s compiler might not be in the top-3 most used C++ compilers (Clang, GCC, MSVC), but it is still very popular and obviously an essential choice to get the best performance on Intel processors.
Moving to LLVM infrastructure is definitely a trend among C++ tool vendors. There are obvious reasons for that – there is a huge community caring and contributing to it, and it’s fully open-source which makes it a perfect choice for tooling. Intel got the latest C++ language standards nearly for free as a result of the migration.
Intel recommends users migrate to a new compiler as the old one will soon be moved to a legacy mode with no updates. The migration guide with many useful details is published. The Intel migration announcement also shares a set of benchmarks showing the compile time and performance benefits of the new Intel LLVM compiler.

CLion 2021.3 Roadmap

Following the CLion 2021.2 release in July, we published the vision for our next CLion release coming at the end of 2021. Our major focus is still on performance and eliminating freezes. In addition to that we’ll do our best to simplify user configuration efforts in several ways:

  • Bundle the MinGW toolchain in CLion installer on Windows so you need fewer manual downloads and installations when starting with CLion on that platform.
  • Add the ability to configure the toolchain environment via script (for example, if you use a script to initialize all the compiler environmental variables, including the addition of the bin and lib paths).
  • Bundle Ninja and use it as the default generator for CMake projects, which is an essential default for many CMake projects nowadays.
  • Finalize and release our long ongoing work on custom compilers. When it’s finished, you’ll be able to fill in configuration files (likely in the yaml format) for the compiler not natively supported by CLion, provide supported features, header search paths, defines, etc., and then use them in CLion to get your custom compiler “supported”.
  • For Makefile project users, automatically find executables corresponding to Makefile build targets.

There are also several pain points in the debugger we plan to address, like long STL type names, “show as array” mode for pointer variables, and hex formatting for numerics. Check out the full plans in the blog post.

And finally, 10 years of C++ support in JetBrains tools!

On August 25, 2021 we celebrated 10 years of public support for C++ in JetBrains tools. It all started with AppCode. We were not expecting to come up with decent C++ support, but it turned out that it’s required for proper Objective-C++ support. So we started with macros in Objective-C++ code, STL auto-import, and some C++ completion. In later AppCode versions, we added libc++ support, correct template parsing, some C++11 features support, and Implement/Override for C++ code. But only when Google Test support landed in AppCode did it become serious enough and we started considering a standalone C++ IDE for the JetBrains family.
That’s how the idea of CLion was born. One interesting fact is that the first CLion demo was in September, 2013, by Dmitry Jemerov at JetBrains Day at FooCafé in Malmo, Sweden. Other names we considered for the IDE were CIDELight, Voidstar, Hexspeak, GottaC, and CTrait. Let us know what other facts you’d like to learn about our C++ Tools, CLion, and ReSharper C++.

About the authors

Anastasia Kazakova Anastasia Kazakova (@anastasiak2512)
As a C/C++ software developer in Telecom and Embedded systems, Anastasia was involved in research estimating the broadband capacity of home networks and participated in launching 4G networks. She is now the Product Marketing Manager for JetBrains C++ tools.
Phil Nash Phil Nash (@phil_nash)
Phil is the original author of the C++ test framework Catch2. As Developer Advocate at SonarSource he’s involved with SonarQube, SonarLint, and SonarCloud, particularly in the context of C++. He’s also the organizer of C++ London and C++ on Sea, as well as co-host and producer of the cpp.chat podcast. More generally, Phil is an advocate for good testing practices, TDD, and using the type system and functional techniques to reduce complexity and increase correctness. He’s previously worked in Finance and Mobile and offers training and coaching in TDD for C++.

Developing for ESP32 With CLion on Windows

$
0
0

While browsing Twitch on a slow Saturday night, I came across someone who was using CLion for embedded development for an ESP32 board. One thing that instantly caught my attention was that they used CLion merely as an editor and compiled and flashed the chip on a separate terminal. I asked why they were doing it that way, and they said that setting up a CLion project for the esp-idf development framework was a bumpy road, especially on Windows. Since I never use Windows for development and I’ve never worked with esp-idf, it was a challenge I was willing to take.

This tutorial shows how to set up a project in CLion for ESP32 development on Windows, covering all the necessary steps in great detail. Starting from downloading and installing the esp-idf development framework, we’ll take a closer look at how esp-idf uses specific environment variables and a dedicated Python environment to compile programs.

We’ll create a new CLion project from one of the esp-idf examples and adjust the project settings so that CLion knows about all of the underlying esp-idf dependencies. With the correct project settings, we will close the tutorial by demonstrating some of CLion’s code-insight features and show how to compile, flash, and monitor programs for your ESP32 board directly from within the IDE.

The most important part is to set the ESP_IDF_PATH variable correctly and adjust the PATH variable to include all entries pointing to the .espressif folder. All the necessary settings can be discovered when taking a closer look at what is done by the export.bat script of esp-idf. The second important aspect is that CMake warning messages are meant to be read because they often point directly to missing pieces. We saw that in the video when we needed to set the ESPPORT variable to monitor the ESP32 on the correct port.

Additional Information:

CLion 2021.2.2 Bug-fix Update

$
0
0

The CLion 2021.2.2 bug-fix update is now available for download! You can get the full 212.5284.51 build from our website. You can also get the new version via a patch update, in the Toolbox App, or as a snap (for Ubuntu).

DOWNLOAD CLION

The main highlights include:

  • CMake Presets:
    • Fixed an incorrect CMake macro expansion on Windows (CPP-26401).
    • When inheriting the presets, the toolchain field is inherited (CPP-26165).
  • Makefile projects:
    • Respect the character encoding value in all make processes (CPP-26237).
    • Use custom make settings during make target extraction (CPP-25620).
  • Formatting:
    • Support the case when the base indent is shorter than the tab size and CLion is configured to use tabs (CPP-22692).
    • Fixed an incorrect “File is not opened in a workspace” error when reformatting the code (CPP-26305).
  • Other fixes:
    • On Windows, when using LLDB for MSVC toolchain, the Natvis CustomListItems block with templated types now works correctly with multiple different instances (CPP-26204).
    • A more accurate warning is shown when launching the configuration with Valgrind Memcheck and sanitizers at the same time (CPP-25955).

You can find the full release notes here.

If you’re wondering what’s coming next, please check out the roadmap for CLion 2021.3.

DOWNLOAD CLION

Your CLion team
JetBrains
The Drive to Develop

Viewing all 678 articles
Browse latest View live