Noutați

How To Use C++ Standards In C++ Compiler Options

C++ is a very decent programming language that has a very strong compiler supported by a big community on a range of different platforms. The C++ language definitions, syntax, and functionality are organized into different standards. Those standards are usually named after the year the standard was adopted such as 1998 for C++98, 2011 for4 C++11, 2014 for C++14, and 2017 for C++17. One of the great features of a C++ compiler is you can choose which standards you want your code to be compiled against, before the compilation of your source code. This allows the compiler to check that your code complies with that standard. In this post, we explain what the standards are, how you can view them, how you can check the compatibility of your C++ source code against different standards, and how you can choose to use C++ standards in C++ compiler options. What is a C++ standard? Standards are an international agreement for C++ compilers, made by the IDE and compiler developers of different operating systems (Embarcadero C++ Builder, Microsoft MSVC, GNU GCC, Apple Swift, etc.). They are formal, legal, and very high-level detailed technical documents intended primarily for people writing C++ compilers and standard library implementations.  The current available standards and some of their key features are listed below. How to use C++ standards in C++ compiler options? When we use ‘-std=’ option in a C++ compiler this option type enables or disables some features. We need to use these features to see the effect of each C++ standard option. Personally, I always prefer to use the latest version of the standards in my compilers. However, when programming, sometimes you may have to work on old or legacy C++ source, or you may be programming to another company that uses older standard compilers. Or maybe you just want to check if your code is compatible with a particular standard, or the code uses new standards. At these times, you can use std option in C++ compilers. In general, we can use the -std option to compile to a particular C++ standard. Here are some option examples, -std=c++98 -std=c++11 -std=c++14 -std=c++17 -std=c++20 or -std=c++2a For example, if you want to compile your code with C++11 features, you can use C++ Builder 64bits command line compiler as shown below: bcc64 –std=c++11 myapp.cpp –o myapp For an example, we can write this C++ code below which uses a feature found in the C++17 standard and above. int main() {   static_assert(sizeof(int)==4); // C++17 feature     return 0; } If you are using the C++17 compiler, this code will be compiled successfully because the static_assert feature comes with C++17. If you compile this code with -std=c++11 or -std=c++14 options this time you will get warning which is telling you that you have requested C++ standard version 11, but there is a feature that requires C++ standard version 17 (Until C++17, a message was required w/ static_assert). How to use C++ standards in the C++ Builder compiler options? In C++ Builder CLANG compiler, we can use -std option to compile in previous standards. This option can be used in bcc32c and bcc64, both support these std options below, -std=c++11 -std=c++14 -std=c++17 I should note that, C++11 and C++14 options are partially supported, these options do not have a STL that works with all, so you have the latest STL one for C++17. According […]

Read More

Learn Unicode Character Types and Literals in Modern C++

C++11 brings a lot of improvements and I think one of the most important features were the Unicode Character Types and Literals that allow more support for strings in different languages globally. C++11 introduced a new character type to manipulate Unicode character strings. This can be used in C++11, C++14, C++17, and above. This feature improved interactions in next generation C++ applications, like chat, social media applications, and so on by allowing a more diverse set of language characters and symbols to be displayed as well as emoticons. In this post, we explain what are Unicode character types and literals in Modern C++. What are Unicode character types and literals in Modern C++ 11? Unicode character types and literals allow more support for different languages, characters, and symbols in strings. C++11 introduces new character types to manipulate Unicode character strings. These can be used in C++11, C++14, C++17, and above. This feature improved language support in editor and design applications (i.e. RAD Studio uses Unicode Strings). It also vastly improved interactions in the next generation C++ applications like chat and social media. This is why we can display smiley faces ????, Vulcan hand signals ???? and love hearts ????. C++ Builder implements new character types and character literals for Unicode. These types are among the C++11 features added to bcc32, bcc32c, and bcc64 compilers. 1. New character types C++11 introduces new character types to manipulate Unicode character strings. For more information on this feature, see Unicode Character Types and Literals (C++11). 2. Unicode string literals C++11 introduces new character types to manipulate Unicode string literals. For more information on this feature, see Unicode Character Types and Literals (C++11). 3. Raw string literals 4. Universal character names in literals In order to make the C++ code less platform-dependent, C++11 lifts the prohibitions regarding control and basic source universal character names within character and string literals. Prohibitions against surrogate values in all universal character names are added. For more information on this feature, see Universal character names in literals Proposal document. 5. User-defined literals C++11 introduces new forms of literals using modified syntax and semantics in order to provide user-defined literals. Using user-defined literals, user-defined classes can provide new literal syntax. For more information on this feature, see User-defined literals Proposal document. What are the Unicode character types char16_t and char32_t in Modern C++? With the C++11 standards, two new types were introduced to represent Unicode characters: char16_t is a 16-bit character type. char16_t is a C++ keyword. This type can be used for UTF-16 characters. char32_t is a 32-bit character type. char32_t is a C++ keyword. This type can be used for UTF-32 characters. The existing wchar_t type is a type for a wide character in the execution wide-character set. A wchar_t wide-character literal begins with an uppercase L (such as L’c’). We have a very good post that explains how you can use character literals in modern C++. What are the character literals u’character’ and U’character’ in Modern C++? There are two new ways to create character literals of the new types: u’character’ is a literal for a single char16_t character, such as u’g’. A multicharacter literal such as u’kh’ is badly formed. The value of a char16_t literal is equal to its ISO 10646 code point value, provided that the code point is representable as a 16-bit value. Only characters in the basic multilingual plane (BMP) can be represented. U’character’ is a literal for a single char32_t character, such as U’t’. A multicharacter literal such as U’de’ is ill-formed. […]

Read More

What Is The ‘>>’ Right-Angle Bracket Support In C++?

C++11 brings a lot of improvements over C++98. In C++98, two consecutive right-angle brackets (>>) give an error, and these constructions are treated according to the C++11 standard which means CLANG compilers no longer generate an error about right angle brackets. In this post, we explain this and how to solve the right-angle bracket problem in C++. What is the right-angle bracket problem in C++? Ever since the introduction of angle brackets in C++98, C++ developers have been surprised by the fact that two consecutive right-angle brackets must be separated by whitespace. For example, if you declare two-dimensional vector (int and bool) as below: #include   typedef std::vector vec1;  // OK   typedef std::vector vec2;  // Error In C++98, the first declaration is OK, but the second declaration give errors because of ‘>>‘ (right angle brackets). However, both are OK in C++11 and above. One of the problems was an immediate consequence of the “maximum munch” principle and the fact that >> is a valid token (right shift) in C++. In the CLANG-enhanced C++ compilers, two consecutive right-angle brackets no longer generate an error, and these constructions are treated according to the C++11 standard. This issue was a minor issue in C++98, but persisting, annoying, and somewhat embarrassing problem. The cost was reasonable, and it seems therefore worthwhile to eliminate the surprise. C++98 developers needed to add space between them. If you want to get more information, you can see details here. How can I solve the right-angle bracket problem in C++? If you have C++98 compiler and come across the right-angle bracket problem, you need to add space between two ‘>’ right angle brackets. ‘>>’ should be written as ‘> >’ as shown in the example below. #include   typedef std::vector vec2;  // OK   int main() { } Or you should change your C++ compiler so that it supports C++11 or above. C++17 is recommended. Note that the latest RAD Studio, C++ Builder standard and CLANG compilers supports C++17 features. What is the right-angle bracket support in C++ 11? In the Clang-enhanced C++ compilers, two consecutive right-angle brackets no longer generate an error, and these constructions are treated according to the C++11 standard.This example below with ‘>>’ right angle brackets can be successfully compiled with any compiler that supports C++11 and above. #include   typedef std::vector vec1;  // OK C++11 and above   int main() { } For more information, see the C++11 proposal document at Right Angle Brackets Proposal document

Read More

Create C++ Member Function in Visual Studio

We are excited to announce that Create C++ Member Function can now be used to quickly add constructor and in Visual Studio 17.6 Preview 2. When you have a class with fields, you can add a default constructor, constructor with all fields, equality operator, and . Three dots will appear below a class name to indicate that you can add a member function, and you can hover over them to see the quick action (screwdriver icon). When the default constructor and equality operator are added respectively, the Go to Definition of the operator== is displayed below, showing that the body of the   You can also choose to add a constructor with all fields and an equality operator with all fields respectively, and the Go to Definition will show that the operator== has all the field comparisons.     Future Work This experimental feature will be improved by adding more functions that can save you a lot of typing. Right now, it includes constructor and operator==and we are considering adding more cases,   We have a Developer Community ticket to Improve “Create Member Function”, if you have the same suggestions make sure to upvote it.   Send us your feedback!  Download the latest version of Visual Studio Preview and give the Create C++ Member Function feature a try. Your feedback will be extremely helpful in shaping this experience, therefore, please continue to send your feedback in the comments below or/and via Developer Community. You can also reach us on Twitter (@VisualC), or via email at visualcpp@microsoft.com.   

Read More

Maximize Unreal Engine Development with the Latest Integrations in Visual Studio 2022

Since our announcement last month, the team has been working hard on building a new round of Unreal Engine integrations. Today, we are happy to show you the next set of features that can level up your game development productivity. In this article, you will learn about how to stream Unreal Logs, see Unreal Header Tool warnings in Visual Studio, and discover how you can be more productive working with HLSL files. All features mentioned below are available in the latest Visual Studio 2022 Preview. Curious to see these features in action? I chatted with Leslie Richardson in a special edition of Visual Studio Toolbox to demo many of the recently available game dev features in Visual Studio. Setting Up Unreal Engine Integrations Unreal Engine integrations will only show up when you are working on an Unreal Engine project. To ensure these features are active, double check that “IDE support for Unreal Engine” component is enabled in the “Game development for C++” workload in the VS Installer. Stream Unreal Engine Log We spoke with Unreal Engine developers and discovered the frustration of having to switch between tasks. Furthermore, this was particularly painful when they need to frequently switch between the UE editor and Visual Studio. As part of the continued efforts to reduce this pain, we are happy to introduce the ability to see your Unreal Engine logs without leaving Visual Studio. Upon pressing F5, Visual Studio will stream Unreal Engine logs to the UE Log window. To see the logs from the Unreal Engine Editor, click View -> Other Windows -> UE Log. When the Visual Studio Debugger is attached to your game, logs are streamed automatically. Alternatively, you can enable cross-process capturing by pressing the “Record” button. As a result, you can stream logs even when the debugger is not attached. To filter your logs, click on the “Categories” or “Verbosity” dropdowns This feature is currently an experimental feature, we would greatly appreciate feedback from you. Leave your thoughts by commenting on Unreal Engine Log Feedback. Code Analysis for Unreal Engine Code Analysis is an important part of the software development workflow. By creating opportunities to identify potential errors prior to compilation, you can save valuable time in your developer inner-loop. Today, we are adding the first of many Unreal Engine specific Code Analysis checks designed to make you more productive. In Visual Studio, you can now see warnings and errors generated by the Unreal Header Tool. Upon saving a file, Visual Studio will run the Unreal Header Tool in the background. Next, Visual Studio will display any warnings or errors in the Error List or as a purple squiggle in the editor. For additional information, please visit the documentation page for Unreal Header Tool. This feature is off-by-default. To enable the feature, please go to “Tools -> Options -> Environment -> Preview Features” and check the box by “Code Analysis with Unreal Header Tool (C++)”. We look forward to hearing from you about UE Code Analysis. Please leave feedback by commenting in the UE Code Analysis Feedback Ticket. Stay tuned for more Code Analysis checks in the upcoming previews. Creating shaders in game development is an important workflow for game developers. We worked with Tim Jones, the author of the popular HLSL Tools extension, to bring syntax […]

Read More

C++23’s New Fold Algorithms

C++20 added new versions of the standard library algorithms which take ranges as their first argument rather than iterator pairs, alongside other improvements. However, key algorithms like std::accumulate were not updated. This has been done in C++23, with the new std::ranges::fold_* family of algorithms. The standards paper for this is P2322 and was written by Barry Revzin. It been implemented in Visual Studio 2022 version 17.5. In this post I’ll explain the benefits of the new “rangified” algorithms, talk you through the new C++23 additions, and explore some of the design space for fold algorithms in C++. Background: Rangified Algorithms C++20’s algorithms make several improvements to the old iterator-based ones. The most obvious is that they now can take a range instead of requiring you to pass iterator pairs. But they also allow passing a “projection function” to be called on elements of the range before being processed, and the use of C++20 concepts for constraining their interfaces more strictly defines what valid uses of these algorithms are. These changes allow you to make refactors like: // C++17 algorithm cat find_kitten(const std::vector& cats) { return *std::find_if(cats.begin(), cats.end(), [](cat const& c) { return c.age == 0; }); } // C++20 algorithm cat find_kitten(std::span cats) { return *std::ranges::find(cats, 0, &cat::age); } The differences here are: Instead of having to pass cats.begin() and cats.end(), we just pass cats itself. Since we are comparing a member variable of the cat to 0, in C++17 we need to use std::find_if and pass a closure which accesses that member and does the comparison. Since the rangified algorithms support projections, in C++20 we can use std::ranges::find and pass &cat::age as a projection, getting rid of the need for the lambda completely. These improvements can greatly clean up code which makes heavy use of the standard library algorithms. Unfortunately, alongside the algorithms which reside in the header, there are also several important ones in the header, and these were not rangified in C++201. In this post we’re particularly interested in std::accumulate and std::reduce. accumulate and reduce std::accumulate and std::reduce are both fold operations. They “fold” or “reduce” or “combine” multiple values into a single value. Both take two iterators, an initial value, and a binary operator (which defaults to +). They then run the given operator over the range of values given by the iterators, collecting a result as they go. For instance, given std::array arr = {1,2,3}, std::accumulate(begin(arr), end(arr), 0, std::plus()) will run (((0 + 1) + 2) + 3). Or std::accumulate(begin(arr), end(arr), 0, f) will run f(f(f(0, 1), 2), 3). These functions are both what are called left folds because they run from left to right. There’s also right folds, which as you may guess, run from right to left. For the last example a right fold would look like f(1, f(2, f(3, 0))). For some operations, like +, these would give the same result, but for operations which are not associative (like -), it could make a difference. So why do we have both std::accumulate and std::reduce? std::reduce was added in C++17 as one of the many parallel algorithms which let you take advantage of parallel execution for improved performance. The reason it has a different name than std::accumulate is because it has different constraints on what types and operations you can use: namely the […]

Read More

Even faster builds with Incredibuild 10 and Visual Studio 17.6 Preview 3

Note: This post was co-authored with Incredibuild’s Director of Product Marketing, Yohai West. We are pleased to announce that Visual Studio version 17.6 Preview 3 includes Incredibuild’s most advanced developer acceleration platform: Incredibuild 10. This release includes several notable, new features that empower teams to speed up the development process: Patent-pending Build Cache technology allows developers to cache build outputs so that they can be reused by all team members. A smart and flexible enterprise license management mechanism, managed via a new web-based Coordinator user interface. Incredibuild Cloud optimization automatically manages the best mix of on-demand and spot resources, enabling organizations to use smaller and more affordable machines, while maintaining optimal performance and cost. In this post we’ll detail how these features can improve your daily development. Build Cache – cache what you can; distribute the rest Incredibuild 10’s most significant addition is its Build Cache technology. Incredibuild breaks down development processes into smaller tasks that can be executed independently, and Build Cache saves time and resources by reusing the cached outputs for previously executed tasks. Build Cache extends the incremental builds you are already likely familiar with by providing access to the outputs that your entire team has created. This means that an incremental build only has to build your changes and can rely on the cache when you have merged a teammate’s unrelated changes into yours. Additionally, temporarily working on a different branch won’t cause a large build when you switch back to your original branch. For any task outputs that are not in the cache, the Incredibuild Grid can distribute those tasks across its pool of compute cores. The Incredibuild Grid can allocate a pool of machines to meet the needed capacity for the tasks, including on-premises machines and static and on-demand spot instances provided by Incredibuild Cloud. The machines in the grid don’t need a compiler to be installed or the code to be present, as the Incredibuild Grid takes care of it all. Once those tasks are completed and cached using Build Cache, they never have to be executed again, dramatically reducing build times for your entire team. These features working in tandem means that you can cache what you can; distribute the rest. Build from home without impacting your speed Working from home affects build speeds due to limited upstream bandwidth. Build Cache lets you rely more on downstream bandwidth, giving you greater speed and better performance when starting new builds. With Build Cache you can reuse previous build data stored on your local machine to dramatically reduce build times without impacting your bandwidth. Deployment Examples Build Cache can be deployed in different ways depending on how your Clients connect to Endpoints. A single Client can function as its own Endpoint (local), multiple Clients can connect to a single Endpoint (shared), and more complex or dynamic deployments are possible as well. Local Uses the same Initiator Agents to host the Build Cache Endpoint and Build Cache Client. This means that each agent can only benefit from the cache of builds that were previously run on the same machine. This can be ideal if you are not sharing code with other developers, or if you are working from home with limited bandwidth. Shared Uses a single Agent to host the Build Cache Endpoint. Multiple Initiator […]

Read More

Functional exception-less error handling with C++23’s optional and expected

This post is an updated version of one I made over five years ago, now that everything I talked about is in the standard and implemented in Visual Studio. In software things can go wrong. Sometimes we might expect them to go wrong. Sometimes it’s a surprise. In most cases we want to build in some way of handling these misfortunes. Let’s call them disappointments. std::optional was added in C++17 to provide a new standard way of expressing disappointments and more, and it has been extended in C++23 with a new interface inspired by functional programming. std::optional expresses “either a T or nothing”. C++23 comes with a new type, std::expected which expresses “either the expected T, or some E telling you what went wrong”. This type also comes with that special new functional interface. As of Visual Studio 2022 version 17.6 Preview 3, all of these features are available in our standard library. Armed with an STL implementation you can try yourself, I’m going to exhibit how to use std::optional‘s new interface, and the new std::expected to handle disappointments. One way to express and handle disappointments is exceptions: void pet_cat() { try { auto cat = find_cat(); scratch_behind_ears(cat); } catch (const no_cat_found& err) { //oh no be_sad(); } } There are a myriad of discussions, resources, rants, tirades, and debates about the value of exceptions123456, and I will not repeat them here. Suffice to say that there are cases in which exceptions are not the best tool for the job. For the sake of being uncontroversial, I’ll take the example of disappointments which are expected within reasonable use of an API. The Internet loves cats. Suppose that you and I are involved in the business of producing the cutest images of cats the world has ever seen. We have produced a high-quality C++ library geared towards this sole aim, and we want it to be at the bleeding edge of modern C++. A common operation in feline cutification programs is to locate cats in a given image. How should we express this in our API? One option is exceptions: // Throws no_cat_found if a cat is not found. image_view find_cat (image_view img); This function takes a view of an image and returns a smaller view which contains the first cat it finds. If it does not find a cat, then it throws an exception. If we’re going to be giving this function a million images, half of which do not contain cats, then that’s a lot of exceptions being thrown. In fact, we’re pretty much using exceptions for control flow at that point, which is A Bad Thing™. What we really want to express is a function which either returns a cat if it finds one, or it returns nothing. Enter std::optional. std::optional find_cat (image_view img); std::optional was introduced in C++17 for representing a value which may or may not be present. It is intended to be a vocabulary type — i.e. the canonical choice for expressing some concept in your code. The difference between this signature and the previous one is powerful; we’ve moved the description of what happens on an error from the documentation into the type system. Now it’s impossible for the user to forget to read the docs, because the compiler is reading them for us, […]

Read More

vcpkg 2023.04.15 Release: vcpkg ships in Visual Studio, Xbox triplets, GitHub Actions Cache Support, and More…

The 2023.04.15 release of the vcpkg package manager is available. This blog post summarizes changes from February 25th, 2023 to April 15th, 2023 for the Microsoft/vcpkg, Microsoft/vcpkg-tool, and Microsoft/vcpkg-docs GitHub repos. Some stats for this period: 39 new ports were added to the open-source registry. If you are unfamiliar with the term ‘port’, they are packages that are built from source and are typically C/C++ libraries. 957 updates were made to existing ports. As always, we validate each change to a port by building all other ports that depend on or are depended by the library that is being updated for our nine main triplets. There are now 2,190 total libraries available in the vcpkg public registry. 125 contributors submitted PRs, issues, or participated in discussions in the repo. The main vcpkg repo has over 5,300 forks and 18,400 stars on GitHub.   Notable Changes vcpkg now included with Visual Studio IDE As of Visual Studio 2022 (version 17.6), vcpkg is now added by default for IDE installations that include C++ workloads. Visual Studio users can run vcpkg commands from a Developer Command Prompt for Visual Studio targeting a new version of the IDE – both the ones embedded in the IDE as well as external terminals. You must run vcpkg integrate install to configure the built-in copy of vcpkg as the one for use by the IDE and in order to add enable MSBuild and CMake integration. More details will be shared in a separate blog post (coming soon!).   vcpkg now supports targeting Xbox out of the box with four new community triplets. The appropriate triplet is automatically chosen when using the Gaming.Xbox.*.x64 custom platforms in the Microsoft GDK with Xbox Extensions via the vcpkg integrate functionality. This makes it easy for developers to build open-source dependencies for this platform. Thank you to Chuck Walbourn from the Xbox organization for preparing these triplets. Triplet Description x64-xbox-scarlett Builds DLLs for Xbox Series X|S x64-xbox-scarlett-static Builds static C++ libraries for Xbox Series X|S x64-xbox-xboxone Builds DLLs for Xbox One x64-xbox-xboxone-static Builds static C++ libraries for Xbox One   Another benefit of these new triplets is for open-source library maintainers, who can validate that their code will build against the WINAPI_FAMILY_GAMES partition used on Xbox using only the public Windows SDK. To learn more about the new triplets and how to use them, visit Chuck’s blog post on the topic.   Official vcpkg Tool Release Architecture is Now amd64 vcpkg tool releases on GitHub are now amd64 (was previously x86), as we do not expect many users to prefer x86 going forward. PR: Microsoft/vcpkg-tool#1005   Binary Caching Support for GitHub Actions Cache The vcpkg binary caching feature now works with the GitHub Actions Cache. GitHub Actions Cache allows you to use a REST API to query and manage the cache for repositories in GitHub Actions. PR: Microsoft/vcpkg-tool#836 (thanks @quyykk!)   vcpkg use now stacks with previous use or activate commands (but not vice versa) For artifacts users, we have made the behavior of vcpkg use and vcpkg activate consistent when used multiple times. You can run vcpkg use after previously running vcpkg use on another artifact to enable both artifacts at the same time. You can also run vcpkg use after a previous vcpkg activate to enable all artifacts invoked by […]

Read More

Fill in the ISO C++ Developer Survey

The ISO C++ developer survey runs every year and is a great help to us in prioritizing work based on what the community cares about. It only takes about 10 minutes to complete and closes tomorrow, so please take the time to fill it out.   Sy Brand C++ Developer Advocate, C++ Team

Read More