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

CLion Starts 2021.3 EAP: Easier Toolchain Configuration, New Debugger UI, Parallel Stacks View, and Type Hints

$
0
0

The roadmap for CLion 2021.3 includes a few interesting features and lots of useful enhancements. Today we are announcing the start of the 2021.3 Early Access Program!

The main goal of the EAP is to collect feedback on the changes and fine-tune the final release. You can give the free EAP builds a try and let us know how you feel about them! Share your feedback in the comments or submit it to our issue tracker. It’s especially important for us to understand if the changes we are making affect your very specific environments or use cases. The earlier you report it, the more improvements we’ll be able to incorporate in the release and first bug-fix updates.

CLion 2021.3 EAP

Build 213.3714.446 is 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.3 EAP

Check out the main highlights and read the post for more details:

Editor enhancements

Type hints

To increase code readability, CLion provides various code hints. For example, parameter hints show the names of function parameters for passed arguments. In the CLion 2021.3 EAP, we added type hints for deduced types.
Decltype hints

The use cases when the hints are present are auto variables, structured bindings:
Structured bindings hints
and lambda return types:
Lambda return type hints

You can disable or enable specific type hints in Settings/Preferences | Editor | Inlay Hints | C/C++ or right from the hint’s context menu.

If the type hint includes the template instantiation, the template arguments can be collapsed by simply clicking on the angle brackets. Also, Ctrl+Click (on Windows/Linux) and Cmd+Click (on macOS) allow navigating to the declaration of the type you clicked on:
Navigation in hints

Postfix completion snippets

Users can now edit names of the postfix completion snippets if you prefer names different from the default ones.

Toolchains and environments became easier

If your environment is stable and you rarely change tools like compilers, you are probably not using the CLion toolchains settings after you have configured it. But for people just starting out with CLion, it’s the first thing they are introduced to. On any platform, to start with CLion, users need to select at least one of the supported environments and configure the toolchain with the compiler, debugger, and other tools. Without that initial configuration projects won’t be loaded correctly.

From CLion users’ feedback, we know that environment and toolchain configuration is challenging, especially on Windows. In this release, we are working on improving the UX and enhancing the existing functionality.

MinGW toolchain on Windows

When getting started with CLion on Windows, there are several options for environments: MinGW, Cygwin, Visual Studio, or WSL. The CLion 2021.3 EAP bundles the MinGW toolchain for quick setup, which you can rely on if you don’t have any other options installed on your machine. The exact version bundled is MinGW-w64 9.0 with languages=c,c++, posix threads, and seh exceptions.
MinGW bundled on Windows

Another improvement for MinGW users is a bundled GDB v 10.2 with Python support (required in CLion). Previously we had a 32-bit version bundled, but we have now switched to a 64-bit version. Since the 10.1 update, 64-bit GDB supports debugging of 32-bit targets on Windows, so you can debug both with it.

Ability to initialize toolchain environment via script

In some cases the environment in which the compiler runs is initialized via a script. It can initialize compiler environmental variables, customize the PATH variable, and more. Sourcing a script instead of setting individual environment variables in the configs is definitely more effective. A typical example where sourcing environment scripts can be used is configuring Yocto.

This works for all types of toolchains and on all platforms. Just go to Settings/Preferences | Build, Execution, Deployment | Toolchains and select Add environment | From file:
Environment script
The sourcing will happen on the first actual usage of this toolchain in the CMake profile or when a Makefile project loaded.

A few known issues include:

  • Lack of error reporting for environment script loading (CPP-26641).
  • No support for the environment variables from environment script for CMake presets (CPP-26576).

CMake update

In CLion, you can use any CMake generator. Previously, when a generator is explicitly specified, CLion switched to CMake File API to support the selected generator. In other cases the legacy approach was used. That means parsing the output of the CMake command run with the Makefiles generator. However, CMake File API is a new and better way to query project information. Now it’s used by default for CMake versions 3.20 and higher.

If you still want to use the old legacy approach, you can turn it on in Settings/Preferences | Advanced Settings:
Legacy generator in CMake

This EAP build bundles CMake v3.21.

Debugger enhancements

New debugger UI

The debugger is one of the most important and widely used IDE features, but its UI was becoming overloaded. In this EAP, we reworked the debugger UI to make it cleaner and more compact to provide you with more space and fit more useful information. Evaluate expression is integrated right in the tool window and merged with Watches, and the control buttons have been grouped more logically.
New debugger UI

Extra actions are available in the extended submenu under the three dots:
Debugger extra

If you really need actions to be available in the debugger toolbar and not in the submenu, you can add them via File | Settings | Appearance & Behavior | Menus and Toolbars | Debug Header Toolbar. This is still a work in progress, and your feedback is very much appreciated!

Parallel Stacks view

Multithreaded applications are always harder to debug as you have to track multiple threads at the same time. In this case, the thread call stack information for all the threads can be helpful.

The new Parallel Stacks view is implemented as a separate tab in the debugger tool window:
Enable Parallel Stack view

The Parallel Stacks view lets you quickly look at all the threads in your application, and check the call paths and execution points of all running threads:
Parallel Stacks view

Improved peripheral and hex views

The peripheral view in CLion was updated to support dim register arrays, cluster, and enumeratedValue tags in SVD files. The hexadecimal view was fixed to display uint64_t values higher than INT64_MAX.

Clang tools update

CLion comes with the Clang-Tidy and ClangFormat bundled, and uses a Clangd-based language engine for many operations. In this EAP we’ve updated the LLVM version to 14.0.0 (you can always check the revision used in CLion in Settings/Preferences | Languages & Frameworks | C/C++ | Clangd). This brings a few new Clang-Tidy checks among other improvements:
Clang-Tidy notification
Make sure to review the list and update the settings if needed.

Static analysis updates

We are continuing to work on making CLion’s data flow analysis more powerful. First of all, it became call-context sensitive, which means it treats different calls differently:

  • Each function is analysed for each call site separately.
  • Parameters and return values for different call sites are analysed separately.

This type of analysis enhances the existing checks like dangling pointers which can be caught now in more cases:
Dangling pointer in CSA

In this EAP we enhanced the invalidated pointers analysis and covered cases like a dangling iterator:
Dangling iterator

and modified owner (owners passed by non-const reference are assumed to be modified):
Modified owner

We continue our work on getting more examples from the Herb Sutter’s Lifetimes proposal be caughts by the CLion’s code analysis.

There are also other improvements and bug fixes in the CLion’s data flow analysis and more MISRA rules are now supported.

The full release notes are available here.

DOWNLOAD CLION 2021.3 EAP

Your CLion team
JetBrains
The Drive to Develop


CLion 2021.3 EAP: Multi-threaded FreeRTOS Debugging, Ninja as Default CMake Generator, and More

$
0
0

CLion 2021.3 EAP was launched last week with an impressive list of things to try out:

  • New type hints in the editor
  • New debugger UI
  • Parallel Stacks view
  • Enhancements in toolchain and environment configuration
  • Improvements to DFA and MISRA checks

If you haven’t yet downloaded and installed the 2021.3 EAP, now is a good time to do so! Today we are announcing the second EAP build.

Build 213.4293.2 is 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.3 EAP

Here are the main highlights:

Multi-threaded FreeRTOS debugging

FreeRTOS thread view was introduced in CLion 2021.2. We’re continuing to work on bringing more useful information to this view. We have now added the following information to the view:

  • Task table shows a list of tasks with status information.
  • Queue table shows currently active queues, semaphores, and mutexes.
  • Timer table lists the software timers.
  • Heap Usage table shows the current heap usage and memory block allocation.

These tables are located in two new tabs in the debug toolwindow:
FreeRTOS views in debugger

These views depend neither on the debug probe being used, nor on the debug configuration, but GDB is required. For it to work correctly, several definitions should be present in FreeRTOSConfig.h:

  • configUSE_TRACE_FACILITY needs to be set to 1, to display task numbers and queue types.
  • configMAX_TASK_NAME_LEN needs to be greater than zero, to display the task name properly.
  • configRECORD_STACK_HIGH_ADDRESS needs to be set to 1, to display the task stack info.
  • Both configUSE_TRACE_FACILITY and configGENERATE_RUN_TIME_STATS need to be set to 1 to collect runtime info (runtime column of the task table).
  • Use configQUEUE_REGISTRY_SIZE greater than zero and vQueueAddToRegistry() to assign a name to a queue, semaphore, or mutex. This is useful as queues have no name by default, unlike tasks (which get a name at creation time).
  • Heap info for the scheme from configUSE_HEAP_SCHEME is taken from FreeRTOS/Source/portable/MemMang/heap_N.c.

FreeRTOS Objects view:
Object View

FreeRTOS Heap view:
Heap view

Ninja as a default generator in CMake

Ninja is one of the most popular and effective CMake generators currently used, so we decided to switch our defaults from Makefile to Ninja. If you are using CMake 3.20 or higher, CLion will use Ninja as its default generator. You can still specify your own generator in the CMake profile settings (Settings/Preferences | Build, Execution, Deployment | CMake) if you wish.

To simplify the usage, we’ve bundled Ninja v1.10.2 into CLion. The bundled version is used if all of these are true:

  • Ninja is selected as a generator in CMake profile.
  • The project is not on WSL or in the remote mode. For Ninja set explicitly or as a default generator in CMake, CLion won’t use the bundled version.
  • You don’t have -DCMAKE_MAKE_PROGRAM set in the CMake options.

System Toolchain on Windows

On Windows, the selection of toolchain options included MinGW, Cygwin, Visual Studio, WSL, and Remote toolchain. Now, there is also the System toolchain. Similar to Linux and macOS, it allows configuring CMake, compilers, and debuggers executables, without selecting a predefined environment. You can still load the environment via script in this toolchain. You might need it for the ARM toolchain or other embedded toolchains on Windows.
System Toolchain

There is an interesting use case you might want to try with the System toolchain on Windows – the new IntelLLVM compiler. To configure it on Windows you’ll need to do the following:

  1. Create the System toolchain.
  2. Source the Intel environment script by setting the corresponding setting in the toolchain to something like C:\Program Files (x86)\Intel\oneAPI\setvars.bat.
  3. Select icx compilers in the toolchain settings for C and C++.

An important note! We are not stating that the IntelLLVM compiler works in CLion. We’ve only managed to configure and make it work in several cases on our side. If you are eager to try the brand-new Intel compiler with CLion, we’d greatly appreciate it if you shared your feedback with us. Let us know here or in the comments section below.

Clangd on WSL

With the WSL toolchain set up for your project, you can build your project and compilers from Linux, and run/debug on WSL, without leaving CLion on your Windows machine. With many language features in CLion working via the Clangd-based engine, we realized that running clangd on Windows for projects on WSL is not effective. The performance could be much better if we ran clangd directly on WSL where the project is. In CLion 2021.3 EAP it now does so for CMake and compilation database projects (for Makefile projects, the change is coming later).

Auto-import fix

Finally, CLion addressed an annoying auto-import issue. Now "" is used instead of <> for header files belonging to the project (part of the CPP-5501).

The full release notes are available here.

DOWNLOAD CLION 2021.3 EAP

Your CLion team
JetBrains
The Drive to Develop

CLion 2021.3 EAP: New Docker Toolchain

$
0
0

The CLion 2021.3 Early Access Preview program is now running and has already brought several useful improvements to the users:

  • New type hints in the editor
  • Parallel Stacks view in the debugger and new views for multi-threaded FreeRTOS debugging
  • Ninja as the default generator in CMake
  • Bundled MinGW and System Toolchain on Windows

The new EAP build, 213.4631.3, 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). A patch update will also be available shortly.

DOWNLOAD CLION 2021.3 EAP

Here are the main highlights:

New Docker toolchain

Currently, many of us are developing in Docker containers, which is generally the easiest way to set up the environment and start working with it. Previously, the recommended way to work with Docker in CLion was to use the Remote toolchain, but there are obvious issues with such an approach:

  1. It requires redundant source code synchronization from the local machine to the container.
  2. Two copies of the source code are stored and some synchronization issues may occur (for example, when disabling and then enabling back the corresponding CMake profile using the remote toolchain).
  3. The build artefacts are stored remotely in the container and not synchronized back to the local machine.

All these issues actually come from the fact that there is no need to treat the docker container as a fully remote machine. Instead, we can mount the project folder to it to resolve all of the above issues.

Starting with this EAP, CLion can work with Docker via the Docker Toolchain:

  1. Go to Settings/Preferences | Build, Execution, Deployment | Toolchains.
  2. Add a new toolchain, select Docker type.
  3. Create a docker server and select it in the toolchain settings.
  4. Select one of the available Docker images.

Wait until the toolchain test passes and you are ready to go:
Create Docker toolchain
You might need to configure additional file sharing in Docker for CLion directories on macOS, which we plan to address later (CPP-26848).

Now you can create CMake profiles using this Docker toolchain:
CMake Profile with Docker toolchain

You can also select it in the Makefile settings for Make-based projects.

Your project will now be built, run, and debugged in the corresponding Docker container. CLion will start it and shut it down after the command is executed. The project folder is mounted into the /tmp/<ProjectFolder> directory in the container.

Docker server settings are available in Settings/Preferences | Build, Execution, Deployment | Docker. CLion also bundles the Docker plugin, which brings the Services tool window and many docker-specific actions to the IDE:
Docker services

Tips: better performance with Docker Toolchain on Windows

To get better performance when working with the Docker toolchain on Windows, we highly recommend using Docker with the WSL 2 backend:

  1. Setup Docker Desktop with the WSL 2 backend.
  2. Enable integration with your preferred WSL distribution (in Settings | Resources | WSL Integration), e.g. ubuntu-20.04.
  3. Put the sources of the project into the WSL filesystem (e.g. \\wsl$\ubuntu-20.04\tmp\llvm) and then open it in CLion with the Docker toolchain.

Code completion fixes

Several issues in code completion were addressed, and it now works inside Google Test macros and the assert macro:
Completion in Google Tests

Improvements in Structure View

You can examine the structure of the file currently open in the editor using the Structure tool window (Alt+7 on Windows/Linux, ⌘7 on macOS) or the Structure pop-up (Ctrl+F12 on Windows/Linux, ⌘F12 on macOS). It is now easier to read, with qualified names for the member functions shown there:
Structure View

The full release notes are available here.

DOWNLOAD CLION 2021.3 EAP

Your CLion team
JetBrains
The Drive to Develop

C++ Annotated September 2021: Papers Voted Into C++23, enable_if vs. requires Benchmarks, More on ABI Breakage, and CppCon Program

$
0
0

We have all September news for you in our latest monthly C++ Annotated digest and its companion, the No Diagnostic Required show.

If you have already subscribed, feel free to skip straight to the news. If this is your first time, let us quickly take you through all the formats we offer. You can choose to read, listen, or watch our essential digest of the 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).

September news

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

Language News

October ISO Plenary

One of the advantages of writing the September edition at the start of October is that we are able to cover the October plenary meeting, which, at the time of writing, has just happened. The plenary is the meeting of the C++ standards committee (WG21) to vote on features of the next version of the standard (among other things).

9 language changes, 14 library changes (of which 4 were retrospectively applied as DRs (Defect Reports) to C++20), two combi papers containing issues from previous meetings, and the starting of a new TS for Transaction Memory! I won’t go into all of them in detail, but here are a few highlights, particularly as they relate to things we’ve discussed here before:

  • P0798 – “Monadic operations for std::optional”. We’ve discussed this a few times – most recently back in May, when I said, “it seems the design is in good shape and we’re getting ready to poll it for inclusion into the working draft.” Making correct predictions is hard, especially about the future, but looks like I got that one right! It was voted into the C++23 draft today.
  • P2128 – “Multidimensional subscript operator”. We covered this one back in April, at which point we commented it was quite a swift turnaround so soon after deprecating the comma operator in subscripting expressions. In another swift turnaround, it’s now coming in C++23.
  • P2321: “zip”. Also discussed in April. Now zipped into the next standard.
  • P0847 – “Deducing this”. This is an important paper, so here’s a brief summary.

In C++ today, every (non-static) member function has an implicit this pointer. Not only is it implicit, but its form is dictated for you. It’s always a pointer, and whether it is a const (or a volatile) is determined by how you annotated the member function. That’s all usually fine, but, especially in generic library code, it can often lead to a lot of duplication. So it would be nice if we could make this an explicit argument – particularly a template argument. That way we could deduce its value category, for a start. That then opens up many further opportunities, such as passing it by value – very useful for cheap types like std::string_view – which may pay a cost of indirection for passing by pointer. We can even deduce a derived type, if you’re calling from what is statically known as a derived instance. That gives us the possibility to do static polymorphism without having to use ugly and intrusive CRTP techniques. There are further possibilities, too, but hopefully this has whetted your appetite enough to go and read the paper.

Contracts

The “Minimum Contract Support […]” proposal gets another revision in P2388r2. This update mostly contains clarifications and expansions on what was already there, as well as a feature test macro. Those are all reassuringly boring, but there has been a lot more excitement going on outside the paper itself.

P2388 was meant to be the uncontroversial minimal subset of contract features. Yet some small concerns have been emerging. Much of these center around the syntax, which carries over the attribute-like notation that was in the ill-fated C++20 contracts. There is some concern that, even if they are not technically attributes, the double-square brackets are sufficiently evocative of attribute syntax, and that misconceptions may arise around, for example, what it means for compilation. There are also concerns that it may lead to incompatibilities with C’s adoption of this important feature.

Furthermore, while P2388 defers having to deal with the conundrum of postconditions that refer to mutable parameters (is it the value on exit, or a copy of the value on entry?) – by requiring that only const or reference parameters may appear in a postcondition – there is concern over whether locking in a syntax without addressing it now will restrict our options in the future.

As a response to all of this, one of the authors of P2388 started work on a new paper that explores just an alternate syntax. This new paper is not published yet, so I won’t go into the details. But I will say that, at least at this stage, the syntax takes some cues from lambdas – most notably by employing (optional) capture lists to specify how parameters are handled. Of course this all raises its own questions and these ideas are being actively discussed at the time of writing, ahead of a formal write-up, so the details may change. It remains to be seen whether the possibility of this new direction sets us back enough that contracts will miss the C++ 23 design cut-off. While many of us are keenly awaiting having even minimal contracts support in the language, we also want to see this done right. If we have to wait, then we will wait.

P2415R1 – What is a view?

This paper actually came out in July, then it was revised in August, but we haven’t discussed it before. It feels familiar, though – perhaps because there were long debates during the C++20 process about what constitutes a view and whether they are regular, semi-regular, or something else. For most developers these discussions may have seemed very abstract, and perhaps time and effort that could have been better spent elsewhere. But establishing a strong model is actually very important and has consequences long down the road. P2415 is more in the domain of dealing with those practical consequences – going back to what we were originally trying to model and adjusting our interpretation.

In C++20, views should be cheaply copyable or move-only – but in any case should be cheap to destroy (or rather, destruction should be O(1) – ruling out them containing copies of the data they are viewed over).

But that conflicts with a natural desire to be able to treat containers as views, themselves. If you have an rvalue container (e.g. returned, by value, from a function), then you get lifetime issues if the view can live longer than the container. That’s painful because, if the contained data is moved into a view, then there is no additional runtime overhead. So this paper proposes to relax the restriction on destruction, so views are allowed to be owning.

As always with these things, there are more subtleties to it – and this paper has not been without its critics. But these don’t seem to have been enough to prevent it from being voted into the working draft for C++23 during the plenary meeting and applied as a DR to C++20.

Views on views all the way down

While P2415 was from July and August, the September mailing has seven papers that relate to views – all but one of which are new papers! Five of these are from Barry Revzin and Tim Song, the authors of P2415, and they have almost contiguous paper numbers, so clearly submitted as a batch.

The two from Barry are P2446R0 (“views::move”) and P2441R0 (“views::join_with”). Tim’s are P2442R0 (“Windowing range adaptors: views::chunk and views::slide”) and P2443R0 (“views::chunk_by”). They also co-authored P2439R0, which is actually just slides that cover P2415R1 (“What is a view”). These guys certainly like to share their views!

The other two are David Olsen’s P2408R1 (“Ranges views as inputs to non-Ranges algorithms”) and Nico Josuttis’s P2432R0 (“Fix istream_view”). That last one was also just voted into the working draft for C++23 as well as being applied to C++20 as a DR.

Learning

A compile-time benchmark for enable_if and requires

Arthur O’Dwyer ran some interesting benchmarking tests (part I, part II) to determine which constraints methodology is faster: SFINAE using std::enable_if or C++20 constraints using the requires keyword. Tl;dr: there is no clear winner across all compilers. The results differ from one compiler to another, and they also depend on the generator selected to produce translation units for the tests.

Several options for the SFINAE std::enable_if in the test come from the libc++ approach that changed back in 2019, when standard enable_if_t usages were updated to a slightly different technique with fewer instantiations and more type aliases being used. Another variation comes from either using the extra-value-parameter or extra-type-parameter approach in the generator.

All the tested options are described in the blog post. Interesting observations from the benchmarking results include:

  • On Clang, the requires approach performs significantly worse in all tests. The return-type SFINAE approach gets the same low scores in the test that relies on template argument deduction instead of explicitly specializing the function.
  • On GCC, the requires approach shows average results. The extra-value-parameter approach always shows the best results.
  • On MSVC, the requires approach performs worse; the number of overloads in the test grows, but the share of the curve is different from the others. The return-type SFINAE approach wins out when explicitly specializing the function, but shows the worst results in the test that relies on template argument deduction.

Benchmark results

C++ Return: std::any, std::optional, or std::variant

Rud Merriam wrote a guest blog post for the C++ Stories blog, sharing a practical example from robotics. The author explores solutions to a typical problem – how to handle requests that can bring data or no data at all, and how to avoid a test for no data after calling a decoding function each time. The article constructs and compares the following solutions: std::any, std::optional, and std::variant.

std::any can contain a value of any type without any specification of the type, and this looks quite flexible. But it turns out that you can’t avoid specifying a type, because you need it for the return data function.

std::variant is analogous to a union. std::optional is the closest to the problem specification (holds a value or no value). There is also an implementation that does not use inheritance (you might remember one of our previous episodes covered Arthur O’Dwyer’s article on why it’s unsafe to inherit from standard library types).

The article led to a long discussion thread with many proposals and improvements, which can be very useful if you are solving a similar task.

Coercing deep const-ness

Barry Revzin wrote a blog post about the const-qualification exception to the template deduction. The problem is that the function template that gets a pointer to a constant object of type T can actually be instantiated with a pointer to a mutable object. The blog post explores a few ways to force const-ness in this situation. The trick is that we don’t want to just require the incoming type to be constant – we want to force it to become constant.

The author tries using span, C++20 concepts, and some code manually converting to const, with various degrees of success. He then covers some possible solutions built into the language itself, which have been discussed in the community but don’t exist yet, such as deduction guides for function templates and C++0x (not C++20) concepts, which can alter interfaces. With the latter, you could indeed transform the result of calling the function on the underlying type and as a result, even if the argument were a mutable range, the parameter would still be a constant.

Binary Banshees and Digital Demons: a long read on ABI breaks

JeanHeyd Meneide wrote a treatise about ABI in C and C++, how it can be broken, and what consequences that entails. I encourage you to read it in full as a brief recap would not do it justice. This incredibly detailed article is, in my view, one of the best collections of ABI failures in C and C++, covering the following topics:

  • How changing the copy constructor changes how it’s called.
  • Why it’s a problem to have two identical C functions where one takes long long and the other takes __int128_t.
  • Why you can never write 128-bit or 256-bit literals.
  • The problems with nested functions.
  • Why we’re stuck with a poorly performing std::regex.
  • Why the designers of Win32, POSIX, and Ethernet protocols libraries reserve bits just in case.
  • The std::format locale issue.
  • The MSVC story behind [[msvc::no_unique_address]] (which you can also find below in this digest).

The author shares a lot of his frustrations with how deeply things are affected by the ABI contract. But putting feelings aside, the article provides invaluable insight into what is one of the biggest issues in modern language evolution.

Tool updates

MSVC C++20 and the /std:c++20 switch

In the beginning of September, Microsoft announced a sufficient level of C++20 support in MSVC (Visual Studio 2019 version 16.11) and added the /std:c++20 switch to the list of available switches. This means C++20 now has a stable switch and ABI compatibility is guaranteed (which is not the case for /std:c++latest).

There is an interesting point regarding the ABI break in the announcement. The MSVC compiler ignores attributes that are not known, as allowed by the standard. This means the new C++20 [[no_unique_address]] can cause issues. For example, compiling the same code under /std:c++17 and /std:c++20 switches can lead to different object layouts and thus to linking incompatibilities. In addition, linking with code compiled by an older compiler version might result in an ODR violation, for the same reasons.

To mitigate these issues, Microsoft decided to postpone the optimization for the attribute until the next ABI breakage in the MSVC. If you still want to force the optimization, consider using another new attribute, [[msvc::no_unique_address]]. It works in versions VS 2019 v16.9 and higher, and for all compiler switches.

CLion 2021.3 EAP with enhancements for toolchains and the debugger

CLion’s third major release this year is now in early preview. The team has prioritized the debugging experience, especially embedded development, as well as making environments and toolchains easier to configure.

The CLion debugger has received an updated UI, with its main tool window and many panels rethought and streamlined. New tabs have been added like Parallel Stack View and FreeRTOS with tables of tasks, queues, timers, and a heap usage view. For embedded development, the debugger’s peripheral and hex views have been improved.

Environments and toolchains are now easier to set up thanks to the bundled MinGW and Ninja (which is now the default CMake generator in CLion), as well as the ability to configure an environment by sourcing a script.

Last but not least, CLion’s taking another step to make your code more readable, this time by bringing type hints for deduced types to the editor. The hints show the actual type in auto variables and structured bindings, which should be useful for modern C++ where types can be omitted.

ReSharper C++ 2021.3 EAP helps modernize your C++ code

Both ReSharper and its sibling, ReSharper C++, are now available for Visual Studio 2022 Preview. Visual Studio finally became a 64-bit process, which also gives plugins more memory and improves their overall performance and responsiveness on large solutions.

As for product-specific improvements, ReSharper C++ helps encourage the adoption of recent changes in the language as well as best coding practices:

  • The new standard library functions contains, erase, erase_if, make_shared_for_overwrite, and make_unique_for_overwrite are actively promoted.
  • Modern best practices are suggested, such as removing a redundant elaborated type specifier, using a while-loop in some cases, applying the [[nodiscard]] attribute to a function without a return value, and more.

ReSharper C++ also helps you read and understand code more easily, thanks to an updated Quick Info tooltip which now includes the evaluation result for constant expressions.

SonarLint plugin for CLion

According to the results of our developer ecosystem survey, most developers rely on their IDE for static analysis. CLion’s capabilities in this area are vast, but they can be expanded even further with plugins such as SonarLint, released this summer. A new blog post from SonarSource explains how the plugin can benefit CLion users.

The post describes how some reports from the bundled Clang-Tidy can be improved to cover more specific cases, like detecting if parameters taken by pointer or reference could be made const not just for numeric types but for types like std::string, as well.

The most intriguing part deals with security issues. What I personally found really interesting is how the compiler might optimize out the call to memset to clear the passwords in memory when they are no longer used. Switching to calling memset_s is suggested in this situation. And if you are using security and cryptography libraries in your code, there are checks in the plugin that detect many outdated or otherwise weak algorithms being used.

And finally: CppCon 2021 has announced its program

Scheduled for later in October, CppCon 2021 plans to be a hybrid event, and the main program is now live! Four tracks are planned for onsite attendees and five tracks for online attendees. Each talk will be marked with the corresponding access type, and some have both options available. The tracks include Back to Basics, Embedded, and a new Software Design track. And you can still join the conference – at least for online access.

We think the following talk announcements should especially be worthy of your attention:

  • Bjarne Stroustrup will talk about whether we’re managing to reach the aims of C++ and achieve some ideals set. Specifically, he will discuss type-and-resource safe code, generic programming, modularity, and the elimination of the preprocessor.
  • Titus Winters will teach you to design for the long term, discuss configurability versus concise design, and likely share Google’s experience in this area.
  • Herb Sutter will demonstrate the C++ pattern-matching libraries and language proposals that the language committee is currently considering.
  • Jason Turner will explain what constexpr is, give practical applications for constexpr, and help you figure out where constexpr fits into your application or library.
  • Michael Caisse will focus on integrating C libraries and facilities within a modern C++ embedded target.

Phil and I will also each give a talk:

Both of these sessions will be online and will focus on the various aspects and techniques of static code analysis and code quality in general.

See you at CppCon 2021!

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++.

CLion 2021.3 EAP: Custom Compiler

$
0
0

The CLion 2021.3 Early Access Preview program has now begun and it includes several useful new features for you to try:

  • New type hints in the editor.
  • Parallel Stacks view in the debugger and new views for multi-threaded FreeRTOS debugging.
  • Ninja as the default generator in CMake.
  • Bundled MinGW and System Toolchain on Windows.
  • New Docker toolchain.

The new EAP build, 213.4928.11, is 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). A patch update will also be available shortly.

DOWNLOAD CLION 2021.3 EAP

Using a Custom Compiler in CLion

CLion works with a predefined set of compilers (GCC-based family of compilers, Clang and Clang-cl, Visual Studio C++ compiler, and IAR compiler). The IDE needs to know how to extract compiler information, like compiler predefined macros, in order to correctly resolve the code. That’s why the set of compilers CLion can work with is limited. However, it is common to use a custom compiler not yet known to the IDE, like for embedded development. In this case, a new Custom Compiler can be helpful! This is a way to describe all the necessary information about the compiler in a way CLion understands.

A custom compiler might be a bit tricky to configure from scratch, but is the most general and customizable way to work with rare compilers which may not even be available publicly, but you are using in your project.

Configuring a custom compiler in CLion

To work with custom compilers in CLion, you need to enable it and configure the path to the config file in *.yaml format that contains your custom compiler definition. You can do this in Preferences/Settings | Build, Execution, Deployment | Toolchains | Custom Defined Compiler.
Enable Custom Defined Compiler

Next, open the toolchain you’re going to use and update the path to C and C++ compilers there to your custom compilers:
Custom Compiler toolchain
Alternatively, you can pass the custom compiler via the Makefile or CMake settings.

To check the custom compiler is working:

  1. Load your CMake, Makefile, or compilation database project.
  2. Open any C or C++ file in the editor.
  3. Call the Help | Diagnostics Tool | Show Compiler Info action.

Note: C or C++ files belonging to the project have to be opened, otherwise the action won’t be available in the corresponding submenu.

If everything is okay, you’ll see the compiler type and name as defined in your config file, as well as the list of compiler predefined macros read from the config:
Compiler Info collected
Your code should be resolved correctly in CLion and all code assistance actions should work correctly as well.

That’s it! But what about this *.yaml config file? You need to provide it to CLion, so let’s see how you can create it.

How-to: Examples of custom compiler config files

We have prepared a few examples for you. You can use them as-is or use them as a template for creating your own config files.

  1. Embarcadero Free C Compiler: find the example of the configuration file and the test project on our GitHub.
  2. Texas Instruments Code Generation Tools for MSP430 MCU: find the example of the configuration file and the test project on our GitHub.
  3. SDCC for stm8: find the example of the configuration file and the test project on our GitHub.

How-to: Custom compiler config format

The file contains a mandatory compilers section, with a list of records. Every record has a mandatory description of a compiler and several tags to identify compiler invocation. The invocation is described with:

  • description – the compiler name (mandatory parameter)
  • match-sources – source file name regular expression
  • match-compiler-exe – regular expression with the compiler executable name (in order to use a compiler with such name from any location)
  • match-args – compiler command-line keys
  • match-language – detected language, C or CPP (this is required for CMake only)
  • code-insight-target-name – target platform name for clangd
  • include-dirs – compiler-specific header search paths. Variables allowed in this setting: ${compiler-exe}, ${compiler-exe-dir}, ${user-home}, ${project-path}.
  • defines – compiler-specific macros in the 'name: value' .yaml format. The value can be empty.
  • defines-text – compiler-specific macros in the '#define name value' C format. The value can be empty

Custom Compiler config

The first matching section is used to provide information for the compiler invocation (i.e. source file) to the CLion language engine, including a list of system-defined macros, target platform name for clangd, and a list of system header folders.

A few tips to note here:

  1. Parts of the .yaml file may be reused using standard YAML anchor/alias syntax. There may be a non-structured optional aliases section as a container for the reused parts.
  2. Multiple compilers may be defined using one single file.
  3. If clangd does not support your actual platform, try to use the closest analogue, i.e. same bitness, same byte order, etc.

If you prepare a configuration file for some known yet unsupported compiler in CLion, feel free to publish it and share with the community in the comments section below! We’ll be happy to include the links to our online documentation on the Custom Compiler feature.

The full release notes are available here.

DOWNLOAD CLION 2021.3 EAP

Your CLion team
JetBrains
The Drive to Develop

CLion 2021.2.3 Bug-fix Update

$
0
0

The CLion 2021.2.3 bug-fix update is now available for download! You can get the full 212.5457.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).

Starting from this build, you will need to provide your JetBrains credentials to use the trial product versions. You can read more about it in this blog post.

DOWNLOAD CLION

The main highlights include:

  • Several issues in code completion were addressed, and it now works inside Google Test macros and the assert macro (CPP-26297, CPP-25861).
  • Structure View now includes qualified names for the member functions shown there (CPP-14224).
  • The IDE no longer fails to execute a Google parametric test instantiation (INSTANTIATE_TEST_CASE_P) when the Instantiation Name is empty (CPP-15149).
  • Fixed an issue with detecting the WSL environment on Windows 1909 (CPP-25970).
  • Fixed an incorrect macro expansion in CMake Presets (CPP-26646).
  • Fixed a few issues with Makefile projects (CPP-26697, CPP-26804, CPP-26869).

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 or try the CLion 2021.3 EAP.

DOWNLOAD CLION

Your CLion team
JetBrains
The Drive to Develop

JetBrains Brings CppCon 2021 to You

$
0
0

Hi all,

We are always happy to support community initiatives, such as community meetups and conferences, which are a great source of knowledge and experience.

Following our long-lasting video sponsorship of the C++Now conference, we are proud to announce JetBrains has become an official CppCon YouTube channel sponsor!

One of the biggest C++ events in the world, CppCon gathers nearly 100,000 professionals interested in C++ and its ecosystem on its YouTube channel. Keynotes from CppCon, as well as many other regular talk recordings, are often watched and shared widely in the community. Bringing first-class video recordings to the channel is a great effort by the dedicated conference team, and we are happy to support it!

To help you benefit from the conference content even sooner, we are delighted to offer early access to some of the recordings from CppCon ’21. In these talks, community leaders, influencers, and top language contributors share their views on the state of C++ and its ongoing evolution. If you are unable to attend the conference in person or online, use this opportunity to keep up with the hottest news from the world of C++.

JetBrains Brings CppCon talks to you

To access these recordings, simply open our dedicated webpage and wait for the recordings to become available!

Here is the list of awesome keynote talks that are coming:

We’ll be publishing the recording soon after the live talk ends. Stay tuned!

By the way, if you are a lucky onsite CppCon conference visitor, go ahead and chat with our new Developer Advocate Timur Doumler, who has just rejoined JetBrains and will attend the conference in Denver. Timur will give a talk about Real-time Programming with the C++ Standard Library and will be happy to chat with you about JetBrains tools for C++, audio/music tech, and low-latency C++.

Your JetBrains C++ team
The Drive to Develop

CLion 2021.3 EAP: Enhanced Standard Library Types Rendering and View as Array in Debugger, Zephyr RTOS, and LLDB 13

$
0
0

The new CLion 2021.3 Early Access Preview build, 213.5449.26, is 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). A patch update will also be made available shortly.

DOWNLOAD CLION 2021.3 EAP

Debugger

The new Debugger UI was introduced earlier in 2021.3 EAP. The goal was to improve the general debugging workflow speed and make popular actions more discoverable. Thank you to everyone who tried it out and shared their feedback with us! We’ve analyzed it and decided to bring the old layout back by default in the 2021.3 release cycle. Meanwhile, the new Evaluate Expression field will be kept in 2021.3. We’ll continue to work on a new debugger UI in the next releases.

In this EAP you can also find the following debugger enhancements:

Improved standard library types rendering

When debugging, variable values are some of the most important pieces of information to inspect in the code and can help you to detect code issues quickly. The variable type is also useful as it helps you treat the value correctly. However, some heavily templated standard library types, or types with global and obvious namespace specifiers, can produce long entries in the variables view. The same applies to function signatures in the frame views.

CLion now performs some additional processing to render frames in the frames view and types in the variables view in a more readable and friendly way.

For types (for both variables and frames):

  • Strip auxiliary namespaces, global and function scope specifiers, and standard library ABI version namespaces.
  • Simplify standard library types by replacing standard library types with more readable aliases.

New debugger rendering

For functions in the frames view:

  • Remove return type, if any
  • Hide function parameters
  • Hide template arguments of enclosing types and the function itself, if any
  • Render the name of the function in bold to be easily distinguished from namespaces and enclosing types

Frames view

In addition to functions in the frames view and types in the variables view, the changes also affect how CLion shows stacks in the Sanitizers view:
Sanitizers view

Show pointers as arrays

A new action View as Array… is now available for any pointer variables and adds a watchpoint that renders a pointer value as array. The action is available in the context menu in the variables view. All you need to do is specify the size of the array:
View as Array

Module name and thread ID

There are cases where the code can be compiled to different modules, like template functions. To know in which binary the code is being executed at any moment, the debugger can now show the module name.

Module names in the debugger have to be enabled explicitly. There are 2 ways to do this:

  • Enable Show Module Name in the context menu in the frame view
  • Enable Show module name in Settings/Preferences | Build, Execution, Deployment | Debugger | Data Views

The thread ID given by the OS on thread start can help you identify the thread you are interested in when debugging and is now shown in the thread list along with the thread name.

Module names and thread id

Customizable debugger presentation

To control the presentation of the types, variables, and frames in the debugger, we’ve added new settings to Settings/Preferences | Build, Execution, Deployment | Debugger | Data Views:
Debugger view settings

Here you can control stdlib types rendering, module names, function parameter types and function template arguments, and other things we just recently introduced.

Alternatively, you can control the presentation from the context menu right in the debugger tool window. In Frames view:
Frames view settings

And in Variables view:
Variables View settings

Have you spotted the hex view in these settings? You can now enable it here or in Settings/Preferences | Build, Execution, Deployment | Debugger | Data Views.

Zephyr RTOS thread view

Views with tasks, queues, timers, and a heap usage view were added for multi-threaded FreeRTOS debugging in one of the previous CLion 2021.3 EAP builds. We’re continuing to develop the debugger for RTOS further. Evaluate expression was fixed and now works on RTOS threads.

Zephyr RTOS Thread view is now available! Enable it in Settings/Preferences | Build, Execution, Deployment | Embedded Development | RTOS Integration:
Zephyr RTOS settings

Tasks view similar to the one available for FreeRTOS is now available for Zephyr RTOS:
Zephyr views

Don’t forget to enable CONFIG_THREAD_MONITOR and CONFIG_THREAD_NAME in your project configuration files, otherwise the debugger won’t be able to extract the required information.

LLDB 13

A new LLDB 13.0 is now bundled on macOS and Linux in CLion.

Fixes for type hints

In CLion 2021.3 EAP, we added type hints for deduced types. This build brings a few fixes for them:

  • Improved type hints for dependent types
  • Correct type hint now shown for the initializer list of the templated instance
  • Return type hints now shown for lambdas with the parameter list omitted

The full release notes are available here.

DOWNLOAD CLION 2021.3 EAP

Your CLion team
JetBrains
The Drive to Develop


CLion 2021.3 EAP: VCS Enhancements and Other Fixes

$
0
0

The new CLion 2021.3 Early Access Preview build, 213.5605.4, is 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). A patch update will also be made available shortly.

DOWNLOAD CLION 2021.3 EAP

Find the highlights below.

New Push All up to Here action

Sometimes, you may have several commits that are ready to ship while others are still a work in progress. In such cases, you may want to push only the ones you are confident about.

CLion now allows you to push commits up to the one you have selected in the Log tab of the Git tool window. To do so, pick the commit you want to stop at, right-click on it to call the context menu, and select the new Push All up to Here action:
Push all up to here action

Other enhancements

In this EAP, we polished many of the new features that have already been added to the 2021.3 EAP to prepare them for the release:

  • When initializing the toolchain environment via script, CLion now checks and reports non-existing/incorrect paths to the environment file.
  • Fixed an issue with settings breakpoints when the new Docker toolchain is used (CPP-27153).
  • Attaching for debug to local processes run externally on the machine is now supported for processes run in WSL.
  • Fixed an issue about the value of the @throw tag in Doxygen comments not being highlighted (CPP-27103).
  • Function name proposed by the Extract Function refactoring now follows the selected code style.
  • Code style options for spaces before and after ‘for’ colon and ‘for’ semicolon were separated:C++ code style options update

The full release notes are available here.

DOWNLOAD CLION 2021.3 EAP

Your CLion team
JetBrains
The Drive to Develop

CppCon 2021 trip report

$
0
0

Hello everyone, my name is Timur Doumler (@timur_audio on Twitter), and I have just joined JetBrains as Developer Advocate for C++ tools, including the CLion IDE. I have actually worked at JetBrains as a software engineer in the past, working on CLion’s C++ parser. Apart from that, I have been active as a C++ developer on various projects in the audio and music technology industry (most recently, I co-founded the startup Cradle), as a conference speaker, and as an active member of the ISO C++ standard committee. I am very excited to be re-joining the JetBrains team, and I’m looking forward to engaging with the C++ community in this new and exciting role!

CppCon 2021 was my first in-person conference since the pre-pandemic C++ Siberia in February 2020. After such a long time without any face-to-face meetings, it was a very memorable and rewarding experience. Due to the current US travel restrictions, sadly, the rest of the team could not make it, so for the first time in ages there was no JetBrains booth. I had to jump through quite a few hoops myself to be able to travel to the US, but it was most certainly worth it!

The actual conference experience was not significantly impacted by the Covid pandemic, apart from the fact that only about 260 attendees were on site. In the end, it felt like a good size: it was big enough to be an engaging conference with four tracks of high-quality on-site content, and at the same time small enough that you could get to talk to everyone who was there (a hopeless endeavor at a “normal” CppCon with over 1500 attendees). A few attendees were wearing face masks, and the seats were a bit more spaced out (which I enjoyed because you didn’t have to squeeze past dozens of people in order to find a seat), but other than that it felt very much like a normal C++ conference. After 1.5 years of online-only events, I cannot even begin to describe how great it felt to mingle with real people again!

CppCon lecture

I should mention that CppCon 2021 was a hybrid conference with an online component as well (which in fact had both more speakers and more attendees than the on-site event). However, I did not have a chance to engage with the online bits, as the on-site event was pretty intense, so I won’t comment on them here.

Watch the keynote recordings

Day one

The conference opened with a motivating keynote from Bjarne Stroustrup about the ongoing evolution of the C++ language, followed by a very interesting talk by Jason Turner called “Your new mental model of constexpr”. Jason argued that we should be moving more and more code from runtime to compile time by constexpr-ifying all our functions, and gave examples of code that you can successfully move to compile time even if it seems impractical or impossible at first glance. Performance is not the only benefit here. The interesting thing is that by running your constexpr-ified code at compile time, you eliminate undefined behavior: the code is running inside the compiler, which effectively acts as a C++ interpreter. Everything that, at runtime, would result in undefined behavior (say, accessing a dangling reference) will be caught by this “interpreter” and emitted as compile errors. Jason’s talk took a hilarious turn when he revealed in the middle of the talk that the slide presentation he was showing was itself a binary generated from constexpr-ified C++ code at compile time, and running inside a Commodore 64 emulator.

In the afternoon, I attended David Stone’s talk “Implementing static_vector”. A static_vector is a vector-like container with a capacity fixed at compile time, which holds all its data on the stack inside the object itself. This eliminates the need for dynamic memory allocations and is also very cache-friendly, making this data structure ideal for low-latency applications such as video games, audio processing, and high-frequency trading. While this data structure is widely used, it is surprisingly difficult to implement correctly without violating the object lifetime rules of the C++ standard. These are common problems with such library facilities, and are encountered even when implementing std::vector itself. Because of this, David’s talk will be useful to many developers implementing generic libraries in modern C++.

Day one concluded with the traditional C++ Committee Fireside Chat panel, this year featuring Bjarne Stroustrup, Lisa Lippincott, Gabriel Dos Reis, David Stone, Michael Wong, and Inbal Levi, with Herb Sutter moderating. Many interesting questions were asked. One of the most interesting discussions revolved around the ongoing work on C++23, the next standard, which is quickly approaching its feature freeze date. Compared with the large scope of C++20, C++23 is going to be a smaller bugfix release, and is mainly targeted at completing C++20 with things like standard library support for coroutines and modules, rather than introducing large new language features. The panellists talked a lot about how difficult it is for the committee to adjust to having to work remotely via telecons, as opposed to week-long face-to-face meetings, and how having to work remotely significantly hinders our ability to standardize larger, more complex features. As a C++ committee member myself, I couldn’t agree more with that assessment. I can’t wait until the committee can meet in person again, although this will happen in July 2022 at the earliest, after the feature freeze date of C++23, meaning that all C++23 features will have been developed entirely remotely.

Day two

Tuesday’s plenary session was a talk by Herb Sutter, presenting the way he imagines pattern matching to be added to C++ and how it fits into his larger vision for making the C++ language easier to learn and safer to use. His proposed pattern matching syntax (P2392) uses the new keywords is and as. While it’s too early to know whether or not the C++ committee will approve such syntax (the original pattern matching proposal P1371 does not use it), pattern matching is in my opinion the most exciting and useful new core language feature currently working its way through the C++ committee, and Herb’s solution is certainly very elegant and carefully designed. Even if we end up with a different syntax for pattern matching, I still highly recommend watching this talk: there are a lot of lessons to be learned about language design in general. Plus, Sean Baxter, the author of the Circle compiler (which implements Herb’s proposal) makes a cameo appearance and shows just what his C++ frontend can do.

Other talks I attended today include David Stone’s “Faster, Easier and Simpler Vectors”, building from his earlier talk “Implementic static_vector” and generalising to other interesting variants of std::vector-like data structures, and Ben Deane’s “Composable C++: Principles and Patterns”, a talk with some interesting thoughts about API design in general and the eternal tension between object-oriented and functional programming.

But the most engaging part of today was the so-called “hallway track”, that is, ad-hoc conversations with other attendees in between sessions. It was obvious that everyone on site really enjoyed mingling and socializing after such a long period of being stuck in our homes. I ended up having quite a few conversations about CLion, since I was effectively a walking one-person JetBrains booth: from positive feedback and bug reports from existing users, to curious questions about the latest features, all the way to very specific questions such as whether there is a CLion plugin that lets you view image data during debugging (turns out there is).

Day three

I started my Wednesday with a presentation by Matt Kulukindis from Google, who went into the guts of TCMalloc (Google’s customized implementation of C’s malloc() and C++’s operator new for faster multithreaded memory allocations) in order to replace some of the locking algorithms in there with a lock-free multi-producer multi-consumer queue. Having worked on audio and music production software for many years, where lock-free queues are a ubiquitous and crucial data structure, I was curious how the folks at Google approach such problems. I certainly learned a few new tricks, including how to measure performance of such a queue and how to find race conditions using tooling.

However, the highlight of the day was the talk “‘Deducing this‘ Patterns” by Ben Deane. This was one of my favorite talks of the entire conference (surpassed only by Daisy Hollman’s talk, see below) and I recommend it to everyone who plans to use C++23 after it comes out. “Deducing this” is a new language feature that has already been approved for C++23 by the committee. It is basically a syntax for specifying or deducing the value category (whether it’s an lvalue or rvalue, const, a reference, rvalue reference, etc.) and the full type of the this object that a member-function is invoked on. While I was already familiar with the syntax of “Deducing this“ and had a rough understanding of how the feature works mechanically (we had many discussions on this feature on the C++ committee), I had no idea how many interesting new design patterns this feature enables. The bit I was already aware of is that we can get rid of a lot of duplicated code as we don’t have to implement different flavours (const&, &&, etc.) of the same member function, but we can express it as a template instead. However, I also learned that CRTP (the Curiously Recurring Template Pattern) is now basically obsolete, as “Deducing this“ enables a much easier way to express the same thing. And if that wasn’t enough, we can now finally spell recursive lambdas in C++ (which isn’t even difficult). This is the hallmark of a great new language feature: it solves multiple seemingly unrelated problems at once, and at the end we don’t know how we ever lived without it. This feature alone should be enough reason to get really excited about C++23!

In the evening, I attended the MLOC (Million Lines of Code) Group Community Party, which was another great opportunity to socialize, grab some drinks, and talk about C++ with everyone who made it to CppCon in person.

Day four

Thursday was full of well-known C++ speakers who all made it to CppCon in person. The morning started with a presentation by Andrei Alexandrescu about variant types, of course delivered in his inimitable presentation style. It was followed by a plenary session by Michael Caisse, who reminded us to inspire and be inspired, and told us the story of his career and some interesting glimpses from the life of an embedded developer. Finally, I watched John Lakos talk about using noexcept operators and specifiers safely, promote his new book “Large-Scale C++ Volume I”, and pull off the impossible feat of talking three times as fast as all the other speakers while still delivering a talk that I could follow and that I quite enjoyed.

After the talks, I went to the Meet the Presenters Banquet, which was amazing as usual, followed by a very entertaining lightning talk session where I learned what C++ object lifetime rules have to do with quantum dynamics, and how to use emojis in your C++ code, among other things. I also delivered a lightning talk myself – my first one in over two years! – which I had spontaneously agreed to give and prepared just a few hours prior, showing some code snippets about how C++20 made initialization even more confusing than before.

Day five

On the morning of the last day of CppCon 2021, I presented my own new talk, “Real-time programming with the C++ standard library”. I gave an overview of which parts of the standard library are useable in low-latency and real-time contexts, which are better avoided because they might try to do things like allocating memory or acquiring a lock, and how to squint at the standard in a way that allows you to figure out which category a given standard utility belongs to. The great thing about talking on Friday is that you have the whole week to ask experts on-site questions about the material while preparing it, and the great thing about CppCon (even in pandemic times) is that many of the relevant proposal authors, standard library implementers, and compiler engineers are right there and usually happy to help with figuring things out!

Having delivered my own talk, I went to see Walter E. Brown’s “Correctly Calculating min, max, and More: What Can Go Wrong?” (turns out, a lot! I highly recommend this talk). This was followed by my personal favorite talk of the whole conference: Daisy Hollman’s “What You Can Learn from Being Too Cute”. Her examples of using modern C++ features in creative and surprising ways were as fascinating as they were entertaining, and through her mind-blowing C++ tricks I learned a lot about the language that I didn’t know previously. Did you know that you can throw an exception from inside a local static initializer in order to ensure that a certain function is only called exactly N times during the lifetime of a C++ program? No? Then this talk is for you. Among other things, Daisy also discovered a gaping hole in a C++20 feature that I have authored, CTAD for aggregate types: it turns out that the mechanism that makes CTAD work with aggregate types falls apart completely in the presence of designated initializers, a new syntax for aggregate initialization that was also adopted in C++20. I’m now working on a defect report. Thank you, Daisy!

While I was still pondering on everything I had seen in Daisy’s talk, I went to listen to Jeff Garland give a very useful overview over all the standard library features that are currently slated for inclusion in C++23. And then it was already time for the closing keynote by Sean Parent. I am not going to spoil too much about that one, except that I did know std::move doesn’t move, and std::remove doesn’t remove, but I was completely unprepared for the revelation that std::find doesn’t find.

CppCon rooms

In the end, CppCon 2021 was one of the most enjoyable and memorable C++ conference experiences of my career so far. I would like to congratulate the organizers and give them a huge thank you for all their work. Against all odds, and notwithstanding a global pandemic and international travel bans, they have pulled off something amazing.

Hopefully, next year the JetBrains team will be back at CppCon in full strength!

Watch the keynote recordings

C++ Annotated October 2021: CppCon-dedicated Podcast Episode, Combining String and Templates, Move vs. Copy, and UDL Basics

$
0
0

We have all the October news for you in our latest monthly C++ Annotated digest and its companion, the No Diagnostic Required show.

If you have already subscribed, feel free to skip ahead straight to the news. If this is your first time here, let us quickly take you through all the formats we offer. You can choose to read, listen, or watch our essential digest of the month’s C++ news:

  • Read the monthly digest on our blog (use the form on the right to subscribe to the blog).
  • Subscribe to C++ Annotated emails by filling out this form.
  • Watch the No Diagnostic Required show on YouTube. To make sure you hear about 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).

CppCon-dedicated NDR podcast episode

This month, our edition of No Diagnostic Required is a little bit different from our regular episodes. There are two reasons for that. First, our colleagues from the CppCast podcast (a highly recommended podcast for any C++ developer with great hosts, Rob Irving and Jason Turner) recently noticed that there are other C++ podcasts, but not many of them are regular. CppCast and NDR are, but Cpp.Chat, hosted by Phil Nash and Jon Kalb, hasn’t been released for a while. So I suggested to Phil, who is the host for both Cpp.Chat and NDR, to record a joint episode to breathe some fresh life into Cpp.Chat. Second, CppCon was held live just a week ago. Being the biggest C++ event in the world, it brought lots of new C++ insights, inspiration, and knowledge. There were a lot of new things to discuss at this hybrid event after our year-and-a-half lockdown! It’s a great occasion to have a chat with the organizer, coincidentally Cpp.Chat host Jon Kalb, about this year’s edition and its highlights.

Please welcome the special October edition of No Diagnostic Required show paired with Cpp.Chat:

October news

Easy Way To Make Your Interface Expressive

The article addresses the case of code readability, specifically the case when two parameters of the same type (bool in the example) are passed to the function or as template parameters. How often have you written code like this? How often have you accidentally passed arguments in the wrong order, and broken the code? The article talks about several approaches to avoid the issue, specifically:

  • Expressing the meaning of the parameters in the code itself.
  • Preventing the wrong usage at compile-time.

The list of suggestions starts from a native suggestion to always add comments to the code, then goes through type aliases, and finally, strong types.

Don’t reopen namespace std

Arthur O’Dwyer wrote a blog post proving that users should define template specializations using their qualified names instead of reopening the namespace std. Readability and clean code is one reason for this. A less obvious reason is that names can collide with something in the standard library if the code is placed inside the namespace, meaning you might need to qualify names inside curly braces.

An interesting case is covered at the end of the article. The sample looks pretty typical, but it produces undefined behavior. It reopens the namespace std and inserts an overload of the standard function that works specifically with some user’s type. However, users are not allowed to add new overloads of functions in the std namespace, so the bad practice leads to undefined behavior in this case.

Moves in Returns

Is the return value moved or copied? The classic C++ question was raised and discussed through different samples in this article, written by Philip Trettner. The author doesn’t just discuss where the return values are copied, moved, or directly constructed in memory, but also shows the assembly to analyze the call graph.

The cases discussed are:

  • Directly constructing objects in memory provided by the caller function (“unmaterialized value passing”).
  • Returning a local variable and a named return value optimization. Again, if all the paths through the function end in returning the object, the compiler could use the caller-provided space for the return value, avoiding any copying or moving.
  • Returning a function parameter that behaves differently.
  • Moving from a local variable.
  • Two types with implicit conversion used in the return statement (which, interestingly, is a copy in pre-C++14, and move in newer standards).
  • There are some cases that trigger copy, not move.

C++ Smart Pointers and Arrays

Bartlomiej Filipek posted a couple of new articles about smart pointers on C++ Stories in October. One of them is dedicated to smart pointers and arrays. In this blog post, he looks at ways to create and initialize smart pointers for arrays. Using an interesting addition coming from C++20, he uses a set of functions to skip value initialization to achieve better performance (function with _for_overwrite suffix).

The article also presents a nice summary of the Stack Overflow discussion on whether you need unique_ptr with an array when you have std::array and std::vector. A table comparing the techniques can be used as a practical guide:
Pointer, array and vector comparison
You can look through it and select the conditions that are important or applicable to your case to get a solution.

A Recap on User Defined Literals

There is another article on more expressive and readable code. In his new blog post, Jonathan Boccara provides a refresher on the basics of user defined literals and how to work with them in C++11/14/17. He discusses various useful aspects, like the types allowed for UDL, and some interesting rules to remember (e.g. for suffixes starting with capital letters there should be no space in the prototype between operator"", and the starting underscore of the user-defined suffix should be present).
C++14 and C++17 brough UDLs to the standard library. String literals (C++14) with the s suffix, chrono literals (C++14) with all the time and date related suffixes, and string view literals (C++17) with the sv suffix are discussed in the article.

Combining String and Templates. What could go wrong?

“Stringy Templates” is a nice article discussing the newest language ability to pass strings as non-type template parameters. Non-type template parameters have a very important characteristic – when used with the same template argument, they then define equal specializations. The equality of the template argument might be a compile-time calculation, rather than just using exactly the same entity. C++20 builds on this by allowing class-type non-type template parameters when several conditions are fulfilled, finally making using strings as template arguments possible. The article presents the implementation via the fixed_string type. It also gives an interesting practical example at the end, when given strings should name a valid/registered type.

JetBrains shares CppCon Keynote Recordings

CppCon is a great annual gathering for C++ specialists and those interested in the C++ ecosystem. It brings new proposal announcements, talks about the implementation details of various C++ features, and presents new tools and techniques to the public. After a 2-year break, CppCon’21 is back to the regular in-person format, while also running a Hybrid format. If you were unable to attend the conference in person or online, JetBrains provides you an opportunity to keep up with the hottest news from the world of C++. This year we became an official CppCon YouTube channel sponsor and compiled a special page with the CppCon’21 keynote session recordings.
Timur Doumler, who recently joined the JetBrains C++ team as a Developer Advocate, was among those lucky in-person visitors and shares his impressions of the event in his trip report.

C++ tools evolution: static code analyzers

If you are not yet convinced that static analysis is that helpful and you need more real-world samples to help you decide, check out this article by the PVS-Studio team. It starts with a few interesting examples from CovidSim, StarEngine, and LLVM projects. There are some basic errors that could hurt in some unlucky conditions.

Static code analysis can help prevent such errors, along with code reviews, testing, and techniques like sanitizers. The article is focused around a specific analyzer created by the authors and available both as plugins to various IDEs and as a stand-alone tool. The author shows the various errors it catches in Poco and other projects. The spectrum of issues discussed are memory safety issues, cases of undefined behavior, and always-true code branches.

Finally, the article discusses various static code analyzers and how to choose from the existing selection. It also brings to light the topic of false positives and an analysis baseline.

Language News

As usual, there are some highlights from the world of C++ standardization.

P2465r0 – Standard Library Modules std and std.all

Modules are here – they’re just not evenly distributed (that’s a reference)! While we wait for the tools to catch up and give us an opportunity to see if they live up to their promise, you might feel disappointed that the standard library itself is not available as a module. This paper proposes to fix that with not one, but two standard library modules. Importing std gives you all of the standard library within the std namespace, including all the types and functions inherited from C. Notably it does not export any of the C identifiers in the global namespace, even if the corresponding #include <cheader> might have done. If you have existing code that depended on those identifiers being in the global namespace then importing std.compat is for you. It imports the identifiers exactly as the <cheader> #includes would have done. Note, though, that neither of these modules export any macros. If you depend on any standard library macros, like assert, or the feature test macros, then you still need to #include the appropriate header. With so few macros necessary now, this is probably the best approach, especially if we eventually get contracts (to, among other things, replace the assert macro). Speaking of which …

P2461r0 – Closure-Based Syntax for Contracts

Last month I mentioned that there was a new paper, not yet published, that proposes an alternative syntax for contracts that is based on the lambda capture syntax. That paper has now landed, so we can talk more about it.
P2388 proposes a syntax that looks like attributes, but is not strictly attributes syntax due to the presence of a colon character and other possible future extensions along the lines of C++20 contracts. This paper proposes (almost) exactly the same semantics, but with a different syntax. Instead of looking like attributes, this one looks like lambdas! The three keywords: pre, assert, and post, are preserved, but now they are outside of square brackets and are followed by a(n optional) captures list and a body in curly brackets that contains the checking code. For postconditions the “lambda” may also take an (optional) argument – the return value.

At first it may seem like the “looks-like-attributes-but-not-quite-attributes” problem has been perpetuated, but with lambdas. It’s true, there is some divergence from lambdas as we have today:

  1. The captures list is optional. In fact, for this first MVP step it must be omitted! For “real” lambdas the captures list also functions as the “lambda introducer”, so it is syntactically required to be present, even if empty. In this case, the context sensitive keywords pre, post, or assert, take care of this role, so it makes sense that it can be omitted (in which case it is as if [&] was specified).
  2. Only the postcondition can take an argument, it can only take one argument, and it must correspond to the return type. This is an extra restriction, which we could relax in the future if there was a good reason, so it’s not really a divergence.
  3. There is no return statement (or, rather, it is optional). The conditional code in the body is evaluated and “returned” implicitly. This is actually abbreviated lambdas – which are still in flight – so this syntax is subject to change. However, this is a perfect candidate for abbreviated lambdas.
  4. No type is specified for the return value argument to a postcondition. As in point 3, this is abbreviated lambda syntax (albeit one of the extensions). It is implicitly auto&&.

There are a number of advantages to this syntax that, for me at least, suggest this is a particularly promising direction:

  1. When you look at the code, your intuition and prior knowledge of lambda syntax makes it easy to understand, even with the abbreviated syntax. If and when the captures syntax is allowed, it should also be obvious what it means, especially when reasoning about the value of mutating parameters by the end of the function (although this raises some questions of its own).
  2. There is also an intuitive mental model for what gets executed and when. Captures are evaluated up front. Bodies may be executed at any time or not at all (we don’t see their invocations, so we shouldn’t depend on them), but even if not executed, they must compile.
  3. Some parts of the syntax are overly restricted for the MVP, but it is easy to see how things would be handled in the syntax in the future, like stateful post-conditions.
  4. We will get the benefit of any evolution of lambdas themselves, like abbreviated lambdas and destructuring for return values.
  5. No new “mini language” to learn.
  6. We can use attributes against contracts.
  7. Evolving the semantics is unlikely to have ABI implications for currently foreseeable evolutions.

On the positive side, this proposal has generated a lot of interest and discussion, with many very much in favor of it. On the other hand, if there was any chance we might be able to get minimal contracts support in C++23, this new discussion has probably put an end to that.

P2445r1 – std::forward_like

C++11 introduced move semantics with rvalue references, and std::move and std::forward along with them, to help us achieve “perfect forwarding”. For many developers these can still seem like a bit of a black art, even a decade later, but for library implementers they are essential tools to achieve optimum performance with a clean interface (even if the internals get a bit messy). While std::move turns an lvalue into an rvalue, std::forward aims to preserve the value category of what it is passed, but requires the unqualified type as a template argument to do so. However there are some cases where you need to also consider the value category of another type. This gets quite esoteric in the abstract, but the motivating use-case here is Deducing This. If this is an explicit, templated, parameter then the value category of the owning object becomes generic – which is the main point of Deducing This – but that influences the value category of members that you may need to forward. Unfortunately just taking the decltype of the member is not enough, and there are several models for how these value categories interact with subtle differences that are important in different situations. Understanding the implications of these models and getting them right can be tricky, so having such a facility in the library would be a useful tool to use alongside explicit this parameters when we get them in C++23.

P2012r2 – Fix the range-based for loop, Rev 2

Usually we discuss proposals that are in flight, or have been adopted into the working draft. This one, for now at least, has been rejected! However, there is a strong consensus that the issue it attempts to solve is worth addressing, so it’s likely to come back. Whether it’s in a similar form or with a different approach is yet to be seen. So what’s the problem with range-based for loops?

On the face of it, the problem is just a special case of dangling references. But there is a tight interplay between lifetime extension of temporaries, and the generative nature of range-based for loops, which makes this case particularly pernicious. Take the following example:

for (auto elem : createPerson().getValues()) {
    std::cout << "value: " << elem << "\n";
}

Now if createPerson() returns a temporary, and getValues() returns a reference into that temporary, we end up with a dangling reference. This may not seem intuitive, since the similar looking:

if(auto elem = createPerson().getValues()[0]) {
    std::cout << "value: " << elem << "\n";
}

works due to lifetime extension! The lifetime of the temporary is extended to the end of the statement it was created in, by which time we have copied the element into another variable. It looks like the same should be true of the for loop. But, in fact, the for-loop is specified to be as-if the expression had been written as multiple statements. So the statement that creates the temporary has finished before the loop begins and therefore has already been destroyed! It’s primarily that (effectively) code-generation step that causes the problem. We don’t see the separation of the statement introducing the temporary from the part that assigned an element to the loop variable.

The paper proposes to fix the issue by changing how the range-based-for is specified, so that the lifetimes of all temporaries created in the range initializer are extended. This seems reasonable but was rejected in the committee vote. Why was it rejected? It’s difficult to say too much without quoting individuals, but two objections seemed to be the main causes:

  1. It’s a breaking change. The paper argues that this is a technicality that we shouldn’t meet in practice – except with code that was already broken. Some reviewers disagreed.
  2. There is a separate effort to specify ways that temporary lifetimes could be extended in similar ways. The outcome of that work could supersede what the paper proposes or conflict with it.

Hopefully this will come around again in a way that addresses these concerns. In the meantime, a better option may be to use for_each, which already has the intuitive behavior, and in its ranges form (ranges::for_each) is almost as succinct as the language construct anyway.

Anastasia Kazakova

Twitter: @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

Twitter: @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++.

CLion 2021.3 Goes Beta!

$
0
0

We are fast approaching the release – CLion 2021.3 has now reached Beta! Build 213.5744.5 is available from our website, via the Toolbox App, or as a snap package (for Ubuntu). No license is required, as this build is still free to use.

CLion 2021.3 Beta

DOWNLOAD CLION 2021.3 Beta

CMake generator UI

A new UI for setting the CMake generator was added to the CMake Profile settings page (Preferences/Settings | Build, Execution, Deployment | CMake). You can use the default value for the toolchain selected or set any generator from the predefined list:
CMake generator UI

When the UI field is used, CMake options on the same page are updated automatically and vice versa.

In the first 2021.3 EAP builds we made Ninja the default generator. However, there were a few annoying issues with Ninja and some concerns about whether this change really improved the user experience. So we limited the number of cases where Ninja is used as the default. Now for local toolchains (excluding Remote, Docker, and WSL) and CMake v3.20 and higher, Ninja is used as the default generator for newly created projects or projects opened in CLion for the first time.

Auto import for header files belonging to the project

Another follow-up to a recently introduced change was added to the Beta build. CLion’s auto import now uses "" instead of <> for header files belonging to the project. This default behavior can now be changed by turning off Settings | Editor | General | Auto Import | C/C++ | Auto import local files with quotes.

Other highlights

  • Attaching to the local process now works with WSL debugger (CPP-12054).
  • Performance:
    • Optimized debugger performance (CPP-26408).
    • Addressed high CPU usage when working with LLVM sources on Windows 10 (CPP-26740).
  • Fixed parsing for namespaced concepts (CPP-27040).
  • Fixed several issues with refactorings and intention actions.

You can find the full release notes here.

DOWNLOAD CLION 2021.3 Beta

Your CLion team
JetBrains
The Drive to Develop

Talking to SerenityOS Contributors About Scratch-build C++ Developer’s Playground in Modern C++

$
0
0

Hi all,

SerenityOS is a graphical Unix-like operating system for desktop computers. It’s also a great open-source project that proves that if you want to see something happen, you can do it yourself! In this interview, we talked to Andreas Kling, founder and main contributor to SerenityOS, and Linus Groh, another main contributor to SerenityOS, about the project itself, their experience with C++, and how CLion helps them to develop the project.

Andreas Kling

Andreas has been writing open source C++ for the last 16 years, working on projects like KDE, Qt, and WebKit. Past employers include Apple and Nokia, but nowadays he works full time on SerenityOS, a new Unix-like operating system with the look & feel of a ‘90s office computer. He frequently posts videos of his programming sessions to YouTube and wants to share the joy of systems development with the world.

Twitter GitHub Blog

Linus Groh

Linus started his programming journey in 2012 fiddling around with languages like Python and JavaScript, eventually combining them in his work as a full stack web developer. Later he decided to learn C++ and dive into operating system development by contributing to the SerenityOS project, where he is now a maintainer and active member of the community. You’ll mostly find him working on the system’s own JavaScript engine, LibJS.

Twitter GitHub Website

Hi Andreas, Linus! Can you please tell us a bit more about the project. What makes SerenityOS different from other OSes and what’s the overall goal of the project?

Andreas:
I started the project in 2018 with the short-term goal of keeping myself busy and the long-term goal of building an OS I would be able to use as my main system in the future.
SerenityOS logo
We’re building a complete system from scratch in a single repository with no third-party runtime dependencies. That means we have our own kernel, shell, libraries, desktop, file manager, web browser, etc. It’s all written in modern C++20 with a custom standard library (not STL) used in both the kernel and user space.

Unlike other systems, SerenityOS is primarily made for its own developers. Everyone works on the things they are interested in, or the things they want to have in the system for themselves. There is no ambition to attract regular users, but everyone is welcome to join the development!

Linus:
This autonomy also means that there’s no general roadmap or specific plans. While each individual contributor might have their own goals and TODO lists, there’s no guarantee that any features will be implemented at a certain point in time. In this project, the best way to make sure something gets done is to do it yourself!

At the moment there are no versions or releases either, as everything is still changing rapidly. To try the OS, the latest source code from the repository must be compiled locally – a process that has been made more and more convenient over time.

Can you briefly describe the tech stack you are using in SerenityOS?

Andreas:
The foundation of the system is a monolithic Unix-like kernel (x86 or x86_64) with a POSIX compliant C library as the low-level system API. This provides a familiar interface and allows us to run third-party software like GCC on SerenityOS.

On top of that, we’ve got a large collection of C++ libraries covering everything you could possibly need for a modern desktop system. There are building blocks for graphics, sound, crypto, networking, and also more complex components like TLS, JavaScript, HTML, CSS, PDF, and so on.

The windowing system is implemented similarly to X11, with a control protocol that runs over local sockets, and bitmaps in shared memory being displayed by a compositing window manager.

You mentioned C++20. So you are on the latest C++ standard already. Right?

Andreas:
Yes, we’re using the intersection of C++20 that’s available in the latest versions of GCC and Clang. Since the project has no backwards compatibility concerns, we’re free to stay on the bleeding edge of C++ and we try to take advantage of this.

When I first came across the project, you were using Makefiles, but then moved to CMake. Why did you decide to do that? What were the major benefits of such migration?

Andreas:
There were two main reasons: dependency management and parallelism. With Makefiles, it was a constant battle to keep things building in the right order while spreading the compilation tasks across multiple cores. Moving to CMake was a big task, but one that has paid off greatly, both in terms of maintainability and build performance.

Andreas, in May 2021 you published a story about why you quit your job to focus on SerenityOS full time. How has it worked out for you?

Andreas:
It’s been absolutely great so far! Thanks to the generous support of people around the world, I’m able to put my full attention into the SerenityOS project.

The biggest difference I’ve noticed is that it’s much easier to tackle large-scale refactoring and less glamorous things like project administration etc. When I did this purely as a hobby, I had much less time (and energy) per day, so I preferred to spend it on “funner” tasks.

Andreas, I guess you’ve inspired a few contributors with your story. Do you know why people join the project? What drives them towards SerenityOS specifically?

Andreas:
This is one of my favorite things about this project: everyone has their own personal reasons for joining, but we all share a love for programming and curiosity about technology.

I like to imagine the project as a “developer’s playground” where people can learn how software works by building it inside a monolithic environment. Since we don’t use third-party code, there’s a strong feeling of cohesion within the codebase. It also creates a high degree of accountability within the project. If something needs changing, there’s no need to look outside for an answer.

Linus, you spoke in a recent CppCast episode about learning C++ with SerenityOS, as you’ve never developed in C++ before this project. Was it tough to get started with such a tricky language as C++ with its large heritage? How did you accomplish it?

Linus:
It could have been much tougher in many aspects! I was by no means a programming beginner anymore, having learned and used various languages for various tasks over the years, so I no longer had to familiarize myself with basic programming concepts and could focus on the language specifically instead. This was no different. Initially, my entire goal in learning C++ was to contribute to this OS project that had been fascinating me for a while. This provided a lot of motivation, which of course helped me to keep going, even when progress was slow.

The timing also played a role. I dived into C++ in early 2020, right when the first lockdown started and I had plenty of time at home, which allowed me to spend more time on it than I would otherwise have been able to. Naturally, much of that time was spent investigating and debugging my beginner mistakes :^)

It’s also important to distinguish learning C++ in general from what we call “Serenity C++” – a subset of the language and using simple and understandable patterns – e.g. no exceptions, no STL, no consideration for compilers that can’t use the latest features.

Finally, being around C++ experts helped massively. Not only Andreas but many other contributors answered my countless questions or gave me hints when I knew what I wanted to achieve, but didn’t know what terms to look up (a common occurrence early on!) in the IRC channel and code reviews. It is a great environment for bringing both beginners in the language and experienced programmers – like me, and several others – up to speed.

Linus, what is the most challenging thing for you in the C++ language?

Linus:
In the beginning it was definitely the compiler error messages, often many terminal pages long and not very clear about the true source of the issue. It’s become easier to grasp those over time, but in my opinion there’s still a lot of room for improvement in the various C++ compilers to show clear and human-friendly errors.

Nowadays I sometimes struggle with templates, one of the concepts uniquely new to me from C++. After learning a couple of different languages and using them for a while, many things are somewhat familiar in the next new language – but this wasn’t the case here.

Also going from a “dynamic language mindset” (I had primarily used Python and JavaScript before) to strict static typing – this was not completely new to me, but it requires different approaches every now and then.

SerenityOS tribute to JetBrains

I know you both use CLion for SerenityOS development. How did you start with CLion? What was your first experience like?

Andreas:
Earlier this year, I was looking for a new C++ IDE. I was already happy with my previous IDE, but I also wondered if maybe there was an even better IDE available, and I would never know if I didn’t try others.

So I decided to try something new, and the first one I looked up was CLion. One of the screenshots on the CLion website had a “SerenityOS” project on it, which was very surprising, and I thought this must be a sign! (I later learned that JetBrains had been using our SerenityOS makefiles for testing their makefile support.)

So I decided to give CLion a try. To be honest, it was a bit awkward at first until I got used to the keyboard shortcuts. But within a few days I was moving faster, and it felt really great. I’ve been using it every single day ever since then.

Linus:
Like many other contributors, I started using CLion after seeing Andreas using it in his videos on YouTube – specifically after being offered a free license! I happily ditched my general purpose code editor that I had to configure to a point where it was usable for C++ development specifically, so I really enjoyed the “IDE, not just an editor” aspect of it. Everything worked out of the box, and the few add-ons I installed over time are not playing a part in my core development experience at all – I’d be totally fine without them.

What do you find the most beneficial in CLion for C++ developers?

Andreas:
I really like the fast and fluid navigation tools. Jumping to a specific file/class/function/etc. is super smooth. The integration of static analysis tools is also great. I love seeing tips from clang-tidy alongside compiler warnings.

Lately I’ve been using the 2021.3 EAP, and I’m a huge fan of the deduced type inlays for C++ “auto”!

Linus:
I pretty much agree with Andreas here. Both the navigation within code and static analysis integration are great! Those clang-tidy warnings especially help me to avoid some pitfalls every now and then. I also regularly look up warnings when I come across them for the first time to learn more about the relevant issue. I generally find that the warnings give good advice, so they are part of my learning process :^)

Additionally, I rely massively on automatic code completion, which needs to be fast, accurate, and have an understanding of the language to be helpful – and in CLion it ticks all of these boxes!

Linus, as C++ was a new language for you, was it hard to get used to a new IDE at the same time?

Linus:
Not at all! As mentioned, I had used a different editor (not IDE!) for almost a year after first starting to learn C++ before switching to CLion, so when I did I was already comfortable with the new language.
Additionally I had used both PyCharm and Android Studio for several years in the past, so there was an instant familiarity.

Can you please share some tips for other CLion users to get the most out of the IDE and your favorite action/shortcut?

Linus:
One of my favorite shortcuts is Double Shift, i.e. the Search Everywhere functionality, which makes it incredibly easy to switch to files anywhere in the project or execute actions that would otherwise be hidden somewhere in menus. I cannot remember shortcuts for everything, so being able to search for them by name is helpful.

I also enjoy the Git integration, which is really well done. I’m nowhere near using the full range of available functionality, but everyone will at the very least need to commit, amend, and fix conflicts during development, all of which can be done without ever leaving the IDE.

SerenityOS is an open source project that falls under JetBrains’s OS support program, so now most active contributors to the project can claim a free license from us. Would you recommend that other contributors take this opportunity?

Andreas:
Definitely! I’ve been recommending it to people since I started using it myself.

Thank you both for the interview! And I hope you enjoy working on SerenityOS in CLion!

CLion 2021.3 Release Candidate

$
0
0

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

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

Release Candidate

You need to have an active subscription or a trial license to use CLion 2021.3 RC. No patches will be provided for this release candidate from the stable CLion versions or EAP builds. However, you can expect a patch-update to CLion 2021.3 release from the latest CLion 2021.2 bug-fix update.

DOWNLOAD CLION 2021.3 RC

Check out the main highlights and give the build a try.

Smart Completion

Smart type-matching code completion (Smart Completion) filters the list of suggestions and shows only the types applicable to the current context. In this update we moved this type of completion to a Clangd-based engine and fixed several issues affecting the user experience:

  • We removed the main function from the smart completion list.
  • We removed the std namespace ABI qualifier (__1) from items in the completion list.
  • Function completion now offers types from all possible overloads (CPP-27047).
  • Constructor invocations were added to the completion list (CPP-5350).
  • We added nullptr to the completion list.

We recommend you keep completion via clangd enabled, but if you experience any issues, you can disable it and switch to the CLion’s own engine in Settings/Preferences | Languages & Frameworks | C/C++ | Clangd.

In addition, variables that start with an underscore were added to the completion list in basic completion.

Clangd

Our clangd-based language engine got an update that fixed several regressions:

As of recently, this EAP also supports the Visual Studio 2022 release as a CLion toolchain.

The full release notes are available here. Give the RC build a try, and make sure to report any problems you find to our issue tracker.

DOWNLOAD CLION 2021.3 RC

Your CLion team
JetBrains
The Drive to Develop

CLion 2021.3 Release Candidate 2

$
0
0

Another Release Candidate for CLion 2021.3 is now available!

To install CLion 2021.3 RC2 (build 213.5744.190), download it from the website, update from our Toolbox App, or use this snap package (for Ubuntu). The patch update from CLion 2021.3 RC is also available.

Release Candidate

You need to have an active subscription or a trial license to use CLion 2021.3 RC2.

DOWNLOAD CLION 2021.3 RC2

In this EAP cycle, we added qualified names to the Structure View. This helps to easily distinguish member functions with the same name coming from different classes or from different namespaces. However, the qualified names can be quite long. For the sake of convenience, we’ve introduced a toggle feature. The qualified names are enabled by default in the Structure tool window (Alt+7 on Windows/Linux, ⌘7 on macOS), but can be toggled on and off:
Structure tool window

We’ve also incorporated a setting in the Structure pop-up (Ctrl+F12 on Windows/Linux, ⌘F12 on macOS):
Structure popup

This build also includes a small cosmetic fix to the FreeRTOS object view.

The full release notes are available here. Give this build a try, and make sure to report any problems you find to our issue tracker. The final release is just around the corner – stay tuned!

Your CLion team
JetBrains
The Drive to Develop


CLion 2021.3: New Remote Development, Better Data Views in Debugger, Docker Toolchain, Custom Compiler, Type Hints, and More

$
0
0

We are happy to announce that CLion 2021.3 is now available!

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

CLion 2021.3 release

Check out the highlights and read the post for more details:

DOWNLOAD CLION 2021.3

Beta version of the new remote development functionality

Until now, remote development in CLion was focused on running the project build on a remote host, using remote host compilers and CMake/make, debugging with remote host debuggers, and running the application on the remote target. In this setup, CLion itself runs locally, and your source files are also stored on the local client, with automatic synchronization to the remote host.

However, there are several drawbacks to this approach:

  • It’s not always possible (due to security reasons or otherwise) to store the source code on a local machine, in which case the code can only be located and used on a remote machine.
  • CLion operations, such as indexing, can be quite heavy, so if the local machine is a thin client, there are significant performance issues.

Our users have shared these concerns with us before – CPP-15986, along with a similar problem for the whole IntelliJ platform – IDEA-226455.

We now have exciting news to share –
CLion now comes with long-awaited support for the new remote development workflow!

The main idea is to use a powerful remote machine to execute all IDE operations and to build, run, and debug code – all while running the IDE on a thin local client. A remote host is a physical or virtual machine hosting the source code and running the headless CLion to perform most of the IDE functions. Developers connect to the server with a thin local client (i.e. a physical machine, like a laptop) and use this thin client for development. We hope this setup helps you stay more productive and flexible while allowing you to work securely from anywhere.

You can find the documentation, Getting Started guide, and FAQ in our webhelp. In the following sections, we explain JetBrains Gateway as well as a few known limitations on the new remote development workflow in CLion.

JetBrains Gateway

JetBrains Gateway is our new application that serves as an entry point for all your remote backends. It runs on a Client and can be thought of as a lightweight launcher. It connects a remote server to your local machine, downloads necessary components on the backend, and opens your project in the JetBrains Client. It doesn’t require you to have an IDE installed on your local machine. You can grab the latest version of JetBrains Gateway from the Toolbox app or on the JetBrains website.
JetBrains Gateway
Use JetBrains Gateway as a stand-alone launcher or as an entry point from CLion to connect to a remote server. Check out this Getting Started guide.

It’s important to note that as of right now you are not able to initiate remote development sessions from CLion, but you can do so through JetBrains Gateway.

Known limitations

The remote hosts in this new remote development workflow are still Linux-only for now. Be sure that you have a compatible SSH server on the Linux platform. The Linux platform should have any recent Linux distribution such as Ubuntu 16.04+, RHEL/Centos 7+, and so on.

In the new remote development workflow in CLion, code editing, code analysis, navigation, running/building/debugging your code, and unit tests generally work. There are a few CLion-specific things to note here:

  • CMake-only projects are supported; Makefile and Compilation database projects are coming soon.
  • Process elevation and Run/Debug with root privileges don’t work (CWM-4091).
  • CLion-specific debugger features (Memory View, Disasm) are not shown on a client machine (CWM-507).
  • C/C++, Objective-C/C++, Python, JavaScript, and HTML languages are supported. Swift and Rust are not yet available in this mode.
  • Code coverage is not shown on a client machine (CWM-921).
  • The Sanitizers and Valgrind Memcheck are available, while the Profiler doesn’t start yet in the new remote mode (CWM-4284).

Please note that this is a beta version of the new remote development functionality and we’re still actively working to improve it. Please give it a try and let us know what you think. You can share your feedback or report any bugs here.

Debugger

Better data views in debugger

When debugging, you really want to stay focused on important things. In this release, we customized the way the debugger renders data. The new settings are available in the context menu in the debugger tool window or in Settings/Preferences | Build, Execution, Deployment | Debugger | Data Views | C/C++ (or just Data Views, if all other language debuggers are disabled in CLion). You can now strip the information you are not interested in.

  • In the variables view:
    • Replace standard library types with more readable aliases.
    • Remove global and function scope specifiers and the std ABI version.
    • Hide variable types completely.
  • In the frames view, in addition to the settings mentioned above:
    • Hide function parameters and template arguments.
    • Display module names, which help you guess which binary the code is being run in at any moment and display the thread ID given by the OS on thread start.
  • In the same settings, you can also enable/disable the updated Hex view for numeric variables.

Rendering in CLion debugger

To get a more readable representation of continuous memory storage of the objects of one type, a new View as Array… action is available for any pointer variable. This action adds a watchpoint that renders a pointer value as an array. Just call the corresponding action on a pointer variable and specify the size of the array:
Show as Array

Among other debugger improvements are the Parallel Stacks View and bundled LLDB v13.

Debugger updates for embedded development

The RTOS thread view in the debugger was expanded to Zephyr OS. You can enable the integration in Settings/Preferences | Build, Execution, Deployment | Embedded Development | RTOS Integration. The FreeRTOS thread view which was added to CLion earlier was expanded by adding object and heap views. Learn more from CLion’s webhelp.
FreeRTOS debug

Docker and other toolchain updates

In CLion, a toolchain is a set of all the necessary tools required to build and run your application. Given the variety of possible tools in the C++ ecosystem, it’s important to have a way to configure them in the most concise way. CLion v2021.3 makes toolchains more flexible and easier to configure and customize.

We’ve introduced the Docker toolchain and recommend that you use it instead of configuring the Remote toolchain for your Docker container. It avoids redundant source code synchronization, as the project folder is simply mounted to the container. Create the toolchain in Settings/Preferences | Build, Execution, Deployment | Toolchains, select the Docker image you need, wait until the tool detection finishes, and save the settings. Now you are ready to use your Docker toolchain for project development. Watch the video to learn more:

The following changes are especially useful for embedded development, which allows you to configure toolchains with a huge variety of compilers and specific settings:

  • The Custom Compiler option makes it possible to use compilers that are not supported by CLion natively in CLion. Right out of the box, CLion can detect and work with GCC, Clang, Clang-cl, MSVC, and IAR compilers. For other compilers, you can now provide the *.yaml file that contains your custom compiler definition. Learn more from our webhelp and check out the sample configs on GitHub for several of the most popular cases prepared by the CLion team.
    Custom Compiler examples
  • You can now initialize the environment in which the compiler runs via script in CLion. Such scripts normally set compiler environment variables, customize the PATH variable, and more. A new option for the script was added to the toolchain configuration.

A few Windows-specific enhancements were introduced in CLion v2021.3:

  • The System toolchain can be useful for ARM or other embedded configurations on Windows. It allows you to configure the make executable, compilers, and the debugger without selecting a predefined toolset and environment, similar to Linux and macOS.
  • For those starting with CLion on a Windows machine without any compilers configured, MinGW is now bundled in CLion. The exact version bundled is MinGW-w64 9.0 with languages=c,c++, posix threads, and seh exceptions.

Watch the video to learn more:

The CMake project model has received some updates, too:

  • We’ve updated it to v3.21.1, meaning that CMake Presets v3 are now also supported in CLion.
  • For version 3.20 and higher, CLion now uses CMake File API as its default approach when querying project information. If you prefer the legacy approach, which involves CLion parsing the output of the CMake command that is run with the Makefiles generator, you can still enable this in the settings.
  • Ninja has become a default generator for newly created and newly opened projects in CLion for local toolchains (i.e. excluding Remote, Docker, WSL) and CMake v3.20 and higher. Along with this change, Ninja v1.10.2 was bundled in CLion. Ninja seems to be one of the most effective generators for CMake currently, so we encourage you to use it in your projects. There are still some issues like non-colorized output (CPP-17786), which we plan to address in upcoming versions.
  • A new UI for setting the CMake generator was added to the CMake Profile settings page Settings/Preferences | Build, Execution, Deployment | CMake. Users can use the default value for the selected toolchain or set any generator from the predefined list:Generators for CMake

Type hints in the editor

In some cases it might not be obvious which type is used in a specific location in the code, such as for auto variables, in structured bindings, and for lambda return types. To increase code readability, CLion 2021.3 adds type hints for deduced types.
Type hints in structured bindings

Given that modern C++ code can avoid mentioning types at all, this can be a real help:
Type hints in auto variables

Combined with the parameter hints added in the previous versions, these hints make reading and maintaining code in C++ much easier:
Type hints for lambdas

More powerful and accurate code analysis

CLion 2021.3 includes a list of fixes for Data Flow Analysis. The analysis is now call-context-sensitive. This means it treats different function calls differently without mixing the data taken from them for analysis. CLion’s lifetime analysis, which is implemented via DFA and based on Herb Sutter’s Lifetime Safety proposal, has been enhanced and can now identify dangling iterators and modified owners.
Dangling Iterator

This update also brings new MISRA checks (the up-to-date list of supported checks) and updates LLVM tools including Clang-Tidy to v14.0.0.

Plugin updates

Space IDE plugin updates

Did you know that you can connect CLion to Space to get access to your repositories, code reviews, Automation (CI builds), and packages? You can install the Space plugin manually in CLion.
Merge requests and code reviews are central to the workflow of many development teams. Wouldn’t it be great to be able to work on code and ask for reviews in the same place? The updated Space plugin now lets you do all of this from within CLion!

  • Create merge requests and assign teammates for code reviews from the IDE.
  • Mark files as viewed/not viewed to keep track of where you are in a code review.
  • Add reactions in code review chats to communicate with your team more easily.

Read the documentation to learn more.

Rust plugin updates

IntelliJ Rust provides improved support for declarative macros 2.0. Procedural macro support, an experimental feature at the moment, has received updates as well.

The plugin now fetches full stdlib info, including the dependencies and Cargo features.

The new name resolution engine now supplies data for the Auto-import quick-fix and for completion of items outside the current scope. This makes auto-import available for macros and improves processing of complex re-exports – all while boosting performance.

ML-assisted completion was enabled by default. Crate and version completion in Cargo.toml has been improved significantly thanks to local indexing of the crates.io metadata. The plugin also added a quick-fix to qualify full paths and new refactoring to extract struct fields.

On the running and debugging side, code coverage now works for stable toolchains, WSL support is enabled by default, and the debugger is capable of automatically breaking on “panic!”.

Other changes

A quick glance at just a few of the changes:

  • A new Build directory option was added to Settings/Preferences | Build, Execution, Deployment | Makefile for configuring the directory where all make tasks are executed when the Makefile project is loaded in CLion.
  • Gradle and Gradle Native plugins in CLion are now unbundled and can be installed from our marketplace.
  • A new toggle was added to the Structure tool window and the Structure pop-up to show qualified names for the member functions and to help you more easily distinguish functions with the same names.
  • The new Push All up to Here action allows you to push commits up to the one you have selected in the Log tab of the Git tool window.
  • To improve CLion performance for projects on WSL, the Clangd-based language engine is now run directly on WSL in such cases.

We encourage you to give CLion 2021.3 a try. If you have an active subscription, you can update today. Otherwise, start your free 30-day trial to check out the new features and see what you think!

DOWNLOAD CLION 2021.3

Your CLion team
JetBrains
The Drive to Develop

Watch Docker Toolchain in Action

$
0
0

We recently released CLion 2021.3. One of the most exciting new features in it is a new Docker toolchain that helps you compile, run, and debug your applications in Docker containers. Watch the video to learn more about it:

00:00 Intro
00:20 Preparing Docker with an `alpine` image
01:07 Creating Docker toolchain in CLion
03:40 Docker toolchain on Windows
04:32 WSL2 backend to run Docker
05:35 Docker plug-in

Your CLion team
JetBrains
The Drive to Develop

Virtual Round Table about C++ Ecosystems

$
0
0

At the end of November, I took part in a virtual round table together with experts from Microsoft, Conan, and Incredibuild (the hosts). The discussion focused on the best tools, environments, and ecosystems for C++ developers. We touched on many tools, including compilers, build tools and package managers, IDEs, static and dynamic analyzers, knowledge management tools, and tools for enabling remote configurations.

Together with Cameron DaCamara (Microsoft), Diego Rodriguez-Losada (Conan/JFrog), and Amir Kirsh (Incredibuild), I had a great discussion about how C++ developers select a tool for a certain domain and which criteria are more and less important to developers. It was especially interesting to consider if the open-source aspect matters more than other aspects. Each of us shared our favorite tools in a list of must-haves that we use daily.

We also discussed the past and the future of the C++ ecosystem. We started from the improvements we have seen in the C++ ecosystem in the past five years. Then we shared our thoughts on where we think C++ ecosystems will go in the next decade and how the language and the tools will evolve.

I’d like to share a quick overview of my points here, but I really recommend that you watch the recording to dive deeper into the discussion and learn the thoughts shared by the others:

  • The value of static code analysis grows significantly over the years. C++ developers tend to use analysis tools integrated into their IDEs and have high requirements for them. Clang is adopted by many tool vendors and has evolved because of the community, with ClangFormat and Clang-Tidy tools seen as the de-facto standard. Language developers expect code checks to help adopt the suggested practices along with the compilers (Lifetimes, Contracts, Parameter passing proposals).
  • Even though there are still dozens of project models and build systems in the ecosystem, we see CMake as something very close to a standard. It has grown from 34% in 2017 to 55% in 2021, becoming the absolute leader several years ago.
  • The ISO C++ committee now understands that toolability aspect of the C++ features is very important for further adoption among everyday C++ developers. The tooling study group was formed to take care of this specifically.
  • Remote and distributed development environments are of high importance. It has only sped up since the pandemic.

Timeline:
00:00 – Meet the experts
02:36 – C++ ecosystem categories breakdown
04:40 – How to select a tool for each domain
16:43 – Which C++ tools would you take to a desert island?
28:41 – What improved in C++ ecosystems in the past couple of years?
39:42 – About JetBrains’ Remote Development
40:46 – Compiler upgrades via cloud resources
43:30 – How has the talent pool of C++ developers changed in the past five years?
46:11– The future of C++ and its ecosystems
55:28 – Q&A

Your CLion team
JetBrains
The Drive to Develop

C++ Annotated November 2021: Discussions on C++ Ecosystem, a Book on C++ Core Guidelines, Designated Initializers, and Recent Releases

$
0
0

We have all the November news for you in our latest monthly C++ Annotated digest and its companion, the No Diagnostic Required show.

If you have already subscribed, feel free to skip ahead straight to the news. If this is your first time here, let us quickly take you through all the formats we offer. You can choose to read, listen, or watch our essential digest of the month’s C++ news:

  • Read the monthly digest on our blog (use the form on the right to subscribe to the blog).
  • Subscribe to C++ Annotated emails by filling out this form.
  • Watch the No Diagnostic Required show on YouTube. To make sure you hear about 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).

November news

This month we’re going to focus on a set of contracts-related proposals, starting with a couple we’ve seen before.

P2388R4 “Minimum Contract Support: either No_eval or Eval_and_abort”

The ongoing “MVP” of contracts papers gets another update in the November mailing. This revision includes a few interesting changes.

To start, there’s a new section on the risk of infinite recursion. If a contract is specified in terms of a call to something which itself has a contract, then there is potential for cycles to occur, leading to infinite recursion. A couple of approaches to dealing with this are discussed.

The section on syntax choices now includes references to the closure-based syntax paper we discussed last month, and a new one on the attribute-like syntax, which we’ll discuss shortly.

There are also some clarifications on the models for predicate elision during contract checking, including how sub-expressions may be elided. This can be useful if the same expression, or sub-expression, is evaluated multiple times throughout the call stack.

But perhaps the most telling change is that all references to C++23 as a target have been updated to C++26!

P2461R1 “Closure-Based Syntax for Contracts”

Last month we discussed the R0 of this paper, which lays out one of the alternate syntaxes for contracts that the syntax section in P2388R4 refers to. This new revision removes some of the specific syntax options that didn’t get much support from the committee, clarifies that its intended purpose is about opening up future extension possibilities, and includes a section on predicate elision, in a similar vein to the new section in P2388R4. Here, though, a line is drawn by specifying all-or-nothing elision – eliding sub-expressions is ruled out.

There are many other small tweaks and updates based on the feedback and review that R0 got. It’s all part of the process, but it does indicate that there is a lot of interest in this proposal.

P2487R0 “Attribute-like syntax for contract annotations”

This new paper rounds out the balance between the two competing syntax options by exploring the attribute-like syntax in more depth. In particular it digs into some of the specific terminology where it has been noted that not everyone has the same understanding. As we’ve seen before with contracts, misalignments here can be at the root of big, ongoing misunderstandings – and even arguments!

One of the most interesting sections is a discussion of what the term “Ignorable” means. This is significant in context as there are certain expectations associated with attributes – that even a merely attribute-like syntax evokes – that turn out to be not as well-defined as we might have thought. Does it mean, for example, that expressions within an attribute must be compilable, even if “ignored”?

P1774R4 “Portable assumptions”

This paper is not new, but it has been dormant for a while. Part of the fallout from C++20’s contracts being removed from the working draft centered on the ability to use contracts to hint to the compiler where it could make “assumptions” that could be optimized around. There was a realization that not everyone agreed that this belonged as part of a feature for specifying correctness. There certainly seems to be a lot in common in how they should be expressed (although contracts may get much more complex) – and maybe even in intent (if you state “this should never happen in a bug-free program”, then it seems to follow that the compiler should be able to optimize around that). But conflating the two also introduces some very tricky issues, including time-travel UB, as we discussed back in episode 4. Just introducing a new form of UB at all, in the attempt to make your programs better specified, is a no-go for some people.

Disentangling these things again seems like a sensible approach, and that’s what this paper does. There are already implementation-specific extensions to express assumptions, so there is prior art and working experience. This paper proposes a standard feature to do the same thing – using actual attribute syntax (as opposed to the attribute-like syntax of P2487).

There are some minor quibbles around some details within the committee, but no major roadblocks. At this point it’s still feasible for this feature to make it into C++23, but it’s too early to make any assumptions.

Three reasons to pass std::string_view by value

A new article by Arthur O’Dwyer discusses three performance benefits of using pass-by-value over pass-by-(const)-reference on a std::string_view use case. It’s kind of known for cheap types like int, char*, and std::pair<int, int>, and it should be applied to types like C++17 string_view, C++20 span, and C++2b function_ref, which are explicitly designed to occupy the same category as int and char*.

  1. Pass-by-value makes it unnecessary to load from memory trivial types that are passed in registers and not via the stack.
  2. Pass-by-reference works via the address, so the caller has to spill it onto the stack, whereas pass-by-value can sometimes eliminate the need for a stack frame in the caller.
  3. Pass-by-value provides the callee with a greater number of optimization options, whereas the reference to the unknown object forces the compiler to behave more conservatively.

Meanwhile, if the performance cost of making a copy outweighs all of these benefits, then pass-by-const-reference should be used.

There was an interesting follow-up discussion raised in response to Arthur’s post, which started from a note that Microsoft’s x86-64 ABI does not pass std::string_view in registers. But it is still better to use pass-by-value for the purpose of expanding to other architectures and in universal code across platforms.

Virtual roundtable about C++ ecosystems

At the end of November, I (Anastasia) took part in the virtual roundtable that was hosted by Incredibuild. Together with Cameron DaCamara (Microsoft), Diego Rodriguez-Losada (Conan/JFrog), and Amir Kirsh (Incredibuild), we had a great discussion about how C++ developers select a tool for certain domains and which criteria are more and less important to them. It was especially interesting to consider if the aspect of open sourcing matters more than other aspects. Each of us shared our favorite tools in a list of must-haves and ones that we use daily.

Finally, we discussed the past and the future of the C++ ecosystem. We started with the improvements we have seen in the C++ ecosystem in the past five years. We then shared our thoughts on where we think the C++ ecosystem will go in the next decade and how the language itself and the tools will evolve.

Talking to SerenityOS contributors

SerenityOS is an open source graphical Unix-like operating system for desktop computers. Started in 2018 as a single-developer pet project, it has since grown into a much bigger collaborative project with many developers now involved with it. Interestingly, it’s built from scratch in a single repository with no third-party runtime dependencies. It uses modern C++20 with a custom standard library (not STL) used in both the kernel and user space. Because of the design choice, SerenityOS is a “developer’s playground” where people can learn how software works by building it inside a monolithic environment.

In this interview, we talked to two of the main contributors to the project – Andreas Kling (also a founder) and Linus Groh. We discussed the tech stack and the move from Makefile to CMake, learning C++ with SerenityOS, the user experience of using CLion for the project, and more.

Using Catch2 v3 in CMake with DDS and PMM

This super-short, practical blog post demonstrates how to use Catch2 v3 with CMake. Catch2 has been known as a header-only unit testing framework for a long time. But it was announced that the framework is moving away from this approach in v3. Many users were worried that with these changes the simplicity of attaching Catch2 to the project will be lost. The post addresses the issue with an elegant solution.

The author shows how to attach Catch2 to the project easily with the help of the Drop-Dead-Simple (DDS) tool and the Package Manager Manager (PMM) CMake module. PMM is actually just a small CMake script that manages external packaging tools (right now, it supports Conan, vcpkg, CMakeCM, and DDS). PMM automatically downloads, installs, and controls package managers from within your CMake project. It’s used here for Catch2 and DDS.

The Catch2 DDS package has some limitations but as a general proof of concept it works.

Designated initializers in C++20

In the past there were nice talks by Timur Doumler and Nico Josuttis about the many ways C++ has to initialize even simple things. Now C++20 brings a new one! Designated initializers is a new way to initialize data members.

Designated initializers increase the code readability, especially when compared to using initializer lists, as it explicitly names the data member. This can reduce the number of errors that are introduced from initializer values being swapped or reordered by mistake. Another benefit is its similarity with the C99 approach and the flexibility it provides, as some data members can be skipped in this approach.

The blog post lists the rules that apply to designated initializers. It also discusses the benefits we mentioned above. The example has a link to Compiler Explorer, so you can have a play with it yourself.

Another interesting benefit we’d like to mention here is that we’ve worked on automatic generation of C++20 designated initializers in ReSharper C++ 2021.3. It works when completion is triggered and the “designated initialization” item is selected. ReSharper C++ will then automatically insert the designators for all the class fields and all you have to do is provide the initial values.

Beautiful C++: 30 Core Guidelines for Writing Clean, Safe, and Fast Code

Kate Gregory and Guy Davidson have announced a new book on C++ Core Guidelines. It will be published around the end of December. It is available for pre-order now in both printed and electronic formats.

It all began with Kate’s CppCon 2017 talk titled “10 Core Guidelines you can’t miss”. Guy then expanded this to 30, bringing more examples and detailed explanations to the practical use cases. The C++ Core Guidelines editors, Bjarne Stroustrup and Herb Sutter, reviewed the book and provided a foreword and an afterword for it. Specifically, Bjarne says the book provides “an emphasis on what benefits can be obtained from following the rules and what nightmares can result from ignoring them.”

If you don’t know where to start with C++ Core Guidelines, start with this book.

Visual Studio 2022 release

Microsoft announced the general availability of Visual Studio 2022. First and foremost, Visual Studio v2022 is now 64-bit, which means more resources are allocated to the IDE so it can handle large code bases better. Another big thing is that Hot Reload gives you the opportunity to update your code and see changes immediately. It is available to native C++ applications that are running under the debugger. We talked about this in the July 2021 edition of our C++ Annotated.

Other highlights for C++ developers include:

  • You can now build and debug natively on WSL 2 without establishing an SSH connection.
  • Enhanced support for CMake Presets.
  • Remote debugging with LLDB from Visual Studio.
  • Support for libfuzzer under the switch -fsanitize=fuzzer.
  • Improved code analysis and many IntelliSense actions.

New remote development options by JetBrains

There were some huge announcements from JetBrains last week that should benefit software developers around the globe. In the new remote reality we have found ourselves in these last few years, remote functions, distributed architectures, and online collaboration have all become essential needs we can’t work without. We have been working on this functionality for a while now, and last week, we opened the preview and beta versions to the general public.

If you are already a user of our IntelliJ-based tools (including CLion, IntelliJ IDEA, PyCharm, and others), you can benefit from the brand-new Remote Development support in these IDEs. You can host your source code, toolchain, and IDE backend on a remote server, and use a local thin client based on the IntelliJ Platform to write, navigate, refactor, run, debug, and test your project. The experience is like working with a project on your JetBrains IDE locally. This is in beta now. Please note there are some limitations specific to CLion.

If you are open to trying new tools, the Fleet announcement might be something you are interested in. What is Fleet? Fleet is a polyglot lightweight editor, which you can turn into a fully functional IDE with a single click of the mouse. It comes with a completely reimagined UI, it is built with a distributed architecture, and it has been developed using JetBrains’ 20+ years of experience of creating IDEs and other developer tools. We opened the Early Preview and within just a couple of days had over 130,000 requests to join it. So for now, the registration to the Preview is closed, but you can subscribe for updates and check out the public preview announcement at jetbrains.com/fleet. Don’t be too upset as C and C++ support is still not yet there. However, our team is working on it and we hope to deliver it in one of the Fleet previews in 2022.

CLion 2021.3 release

The third major release of the CLion IDE this year, CLion 2021.3, is compatible with the new remote development capabilities. This is not the only improvement in the CLion toolchains. The new update adds more flexibility to the current toolchains and adds new ones:

  • CLion adds the ability to configure the toolchain environment with a script by specifying it in the toolchain’s settings.
  • CLion bundled MinGW on Windows and Ninja on all platforms. For newly created or opened projects, the Ninja generator in CMake is now the default (for local toolchains and CMake 3.20 and later).
  • The Custom Compiler option for toolchains, which allows using any compiler not natively supported by CLion. The CLion team has started a GitHub repository with sample config files in Yaml format for some of these compilers. Users are encouraged to send pull requests as well.
  • A new Docker toolchain was introduced in CLion to work with local containers.

As for the editor, CLion 2021.3 now helps with the C++ types that may not be immediately obvious, such as those hidden behind auto specifiers, in structured bindings, or as lambda return types. The new type hints show the deduced types in such cases. There are also many improvements to the debugger: for example, CLion now renders types for variables and in functions, modules, and threads. There are also new settings that allow users to configure the view they consider helpful. You can find more about these and other new goodies in our blog post.

Qt Creator and clangd

The article on the Qt blog from late October, is interesting and wasn’t covered by our October edition of C++ Annotated. It discusses the evolution of the C++ language engines in Qt Creator. It moved from its own implementation to libclang soon after Qt Creator contributors realized that it’s difficult to keep pace with the evolution of modern C++. With the LLVM developers focusing on Clangd and leaving libclang without much attention, Qt Creator then moved to Clangd, a standalone Clang-based daemon with which you can communicate using Language Server Protocol.

Qt Creator now also utilizes a clangd index, which stores information about the whole codebase. It’s used for features like Find References where the AST of the current file doesn’t have enough information – full indexing takes time but the update is incremental.

An interesting side effect of this migration to clangd is that files changed by refactoring actions are auto-saved. This is a direct consequence of the fact that clangd considers only the on-disk state of included header files when parsing a source file.

Anastasia Kazakova

Twitter: @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

Twitter: @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 on Windows? CLion Windows Toolchains to the Rescue!

$
0
0

We recently released CLion 2021.3. As part of this update, we made it easier to configure Windows toolchains in CLion while making them more powerful at the same time. Check out this short video to learn about all the options that are available to you:

00:00 Intro
00:25 Bundled MinGW
01:21 Visual Studio toolchain with MSVC and Clang-cl
03:31 Working with Windows Subsystem for Linux (WSL) in CLion
04:24 Cygwin
05:20 System toolchain
06:16 Remote toolchain
08:59 Docker toolchain

Your CLion team
JetBrains
The Drive to Develop

Viewing all 680 articles
Browse latest View live