Noutați

Create and use Static Library (.Lib) and Dynamic DLLs in C++ Builder

Introduction: This post describes how to create and use Static Library (.Lib) and Dynamic (Run-Time) DLLs in C++ Builder. A library is a collection of pre-compiled code that can be re-used by programs. There are 2 types of libraries: static library and dynamic library. Static Library (.lib) vs Dynamic Library (.dll) A static library (.LIB file) (or archive) contains code that is linked to users’ programs at compile time. The executable file generated keeps its own copy of the library code. A dynamic library (.dll) (or shared library) contains code designed to be shared by multiple programs. The content in the library is loaded to memory at runtime. Each executable does not maintain its replication of the library. What are the differences between static and dynamic libraries? Static libraries (.lib), while reusable in multiple programs, are locked into a program at compile time. Dynamic (.dll), or shared libraries, on the other hand, exist as separate files outside of the executable file. C++ Builder Dynamic Library (.DLL) and Static (.Lib) Library Let’s jump right into creating a C++ Builder Dynamic Library (.DLL) This post is using C++ Builder 11.3 Steps: 1. File | New | Other | C++ Builder | Dynamic Library , select Source type = C++ , check Multi-Threaded, and select Target Framework = No Framework 2. Save the generated project to a new folder:  File | Save Project As | New Folder | CppMyDLL (C:UsersamannarinoDocumentsEmbarcaderoStudioProjectsCppMyDLL).  Rename project to CppMyDLL.cbproj, and rename Unit1.cpp to CppMyDLL.cpp 3. The generated CppMyDLL.cpp file has this code: extern “C” int _libmain(unsigned long reason) The _libmain function is the entry point into the dynamic library. When the dynamic library is loaded, the _libmain function is called. This function usually holds initialization code. 4. To be able to use the DLL and the Client .EXE on any computer (that does not have C++ Builder installed), use:  Project | Options | C++ Linker | Link with Dynamic RTL = False And Packages | RunTime Packages | Link with Run Time Packages = False 5. Build the application (Project | Build). You should get a success Build and Link! 6. Your source code output folder: (C:Users/amannarino/Documents/Embarcadero/Studio/Projects/CppMyDLL/Win32/Debug) should have a CppMyDLL.dll (Dynamic Library) and a CppMyDLL.lib (Static Library). The Static Library (.lib) is automatically generated from the Dynamic Library (,dll). 7. A helpful free utility for seeing the contents of the DLL is Dependency Walker. Dependency Walker is a free utility that scans any 32-bit or 64-bit Windows module (exe, dll, ocx, sys, etc.) and builds a hierarchical tree diagram of all dependent modules. The Download link for Dependency Walker is: https://www.dependencywalker.com/ 8. Next, lets add a function to the CppMyDLL.cpp : double Sum(double a, double b) { return a +b; } Note: DLLs can contain functions that are hidden from the clients, and other functions that are public to the clients. 9. To make this Sum function visible to clients, we add: __declspec(dllexport) like this: double __declspec(dllexport) Sum(double a, double b) { 10. Using Dependency Walker this function SUM shows as @Sum$add To remove the characters @ and the $add (that descibes the function) we add extern “C” to the function, like this: extern “C” double __declspec(dllexport) Sum(double a, double b) { 11. Now, using Dependency Walker, the Sum function shows as: _Sum 12. To remove the […]

Read More

How To Allow Atomics Use In C++ Signal Handlers

C++11 allows the use of atomics in signal handlers, and with the advent of C++ 17 the signal handler feature was again improved. The std::atomic_flag is an atomic boolean type that is guaranteed to be lock-free and can be used in signal handlers. Moreover, the  header in C++ has an integer type std::sig_atomic_t that can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals. In this post, we explain how to use atomic_flag in C++. How to allow atomics use in C++ signal handlers? The header in C++ (or signal.h in C) has an an integer type std::sig_atomic_t that can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals. In this post, we explain how to allow atomics use in C++ signal handlers. Here is how we can use it:   #include   volatile sig_atomic_t flag = 0;   Is there a full example of how to use atomics in C++ signal handlers? Here is an example that has a signal handler and uses sig_atomic_t flag from 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39   #include #include   volatile sig_atomic_t flag = 0;   void handler(int signum) {    flag = 1 ; }   bool signal_check() {   if ( signal( SIGINT, handler) == SIG_ERR )   { return false;   }     if (flag) std::cout

Read More

What Is The Volatile Keyword In C++?

C++ is very strong in every aspect of modern programming. Volatile types are used with the volatile keyword. It is a lesser known type qualifier that is important to read types or objects whose value can be modified at any time. The volatile keyword is useful in memory-mapped applications, generally these are from a hardware device, from a sensor, from an input device, or data from on an IoT. For example, an application reading dynamic data from the registers of a medical robot and decides what to do with that robot arm. In this post we will explain the volatile keyword in C++ and how can we use volatile type specifier. What is volatile keyword in C++? Volatile types are declared with the volatile keyword with a type declaration. Here’s how it is used.   volatile ;   We can use volatile on standard types, structs, unions. We can use them with pointers too. Here are some examples of how to use the volatile keyword in C++.   volatile int x;   volatile unsigned long int *p;   The volatile type specifier is used to change the variable whose values can be changed at any time and don’t have any constant value. The volatile qualifier is important to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Generally used in loops to read data, if you read those kinds of data without volatile types, the compiler and its optimizer can see the loop as useless. Your loop will never read the exact data in that time. For example, in this example:   unsigned int x = 255;   do {    // … }while( x == 255 );   compiler optimization covert this as below:   unsigned int x = 255;   do {   // … }while( true );   In other words, our loop becomes infinite by being true always even if the value of x is changed in some steps inside. To solve this, we can use volatile, thus we will keep reading data from x in do-while loop. Here is the example,   volatile unsigned int x = 255;   do {     // … }while( x == 255 );   If you want to keep reading x data from that address, you must use volatile specifier for the x type. This is why the volatile specifier is needed when developing embedded systems or device drivers. If we need to read or write a memory-mapped hardware device, we can use volatile type specifier on these kinds of data. Because data on that device register could change at any time, so we need to use volatile keyword to ensure that we read data on that time and such accesses aren’t optimized away by the compiler. Another need is some processors have floating point registers that have more than 64 bits of precision and if you need consistency then you can force each operation to go back to memory by using the volatile keyword.   Volatile specifier is also useful for some algorithms, such as Kahan summations, etc. Is there an example to use volatile keyword in C++? Assume that we have an address in our device or in a library of a driver, let’s set this address to a volatile […]

Read More

How To Use Propagating Exceptions In Modern C++?

Modern C++ has many features to aid multi-thread programming that allow applications to be faster and more responsive. The C++11 standard offers the possibility of moving an exception from one thread to another. This type of movement is called propagating exceptions, exception propagation; also known as rethrow exception in multi-threading. To do that, some modifications have been made to the header in C++ and there is a nullable pointer-like type std::exception_ptr. In this post, we explain std::exception_ptr and how to use the rethrow exception method in modern C++. What are propagating exceptions (exception propagation) in modern C++? The C++11 standard offers a nullable pointer-like type std::exception_ptr. The exception_ptr is used to refer to an exception and manages an exception object that has been thrown and captured with std::current_exception(). Here is how we can use both:   std::exception_ptr e = std::current_exception();   In modern C++, a concurrency support library is designed to solve problems in multi-thread operations. This library includes built-in support for threads (std::thread), atomic operations (std::atomic), mutual exclusion (std::mutex), condition variables (std::condition_variable), and many other features. In addition to these useful features, std::exception_ptr is useful in exception handling between threads. They may be passed to another function, possibly to another thread function, so that the exception can be rethrown and handled in another thread with a catch clause. According to open-std, “An exception_ptr that refers to the currently handled exception or a copy of the currently handled exception, or a null exception_ptr if no exception is being handled. If the function needs to allocate memory and the attempt fails, it returns an exception_ptr that refers to an instance of bad_alloc. It is unspecified whether the return values of two successive calls to current_exception refer to the same exception.” The exception_ptr can be DefaultConstructible, CopyConstructible, Assignable and EqualityComparable. By default, it is constructed as a null pointer, doesn’t point to an exception, and operations from exception_ptr do not throw. Is there a simple example of how to use propagating exceptions in modern C++? Here is a simple example that outputs exceptions coming from a thread. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17   std::mutex m;   void throw_exception( std::exception_ptr e) { try { if (e) std::rethrow_exception(e); } catch(const std::exception& e) { m.lock(); std::cout

Read More

How to Use Atomic_flag In Modern C++?

C++11 allows the use of atomics in signal handlers. In C++17 the signal handler feature is further improved. The std::atomic_flag is an atomic boolean type that is guaranteed to be lock-free and can be used in signal handlers. Moreover, the  header in C++ has an integer type std::sig_atomic_t that can be accessed as an atomic entity even in the presence of asynchronous interrupts made by signals. In this post, we explain how to use atomic_flag in C++. What is atomic_flag in C++? The std::atomic_flag is a flag in the atomics library which is known as an atomic boolean type. The std::atomic is guaranteed to be lock-and does not provide load or store operations. In addition, they provide synchronization and order constraints on the program execution. Here is the general syntax since C++11.   std::atomic_flag ;   Here is how we can declare it.   std::atomic_flag flag = ATOMIC_FLAG_INIT;   What are the features of atomic_flag in modern C++? The std::atomic_flag has useful features, these are as follows. The clear() feature is used to set flags to false atomically, in example we can use it with a memory_order as below,   flag.clear(std::memory_order_release);   test_and_set() tests the flag to true and obtains its previous value, in example we can use it with a memory_order in a while loop as we show in the example below:   while (flag.test_and_set(std::memory_order_acquire)) // acquire flag { }   The test() feature is new in C++20, returns the value of the flag atomically, like so:   while ( flag.test(std::memory_order_relaxed) ) // release flag { }   The wait() feature is new in C++20 and it blocks the thread until the atomic value changes and it is notified. Here is an example:   wait ( true, std::memory_order_relaxed);   in C++20, there are notify_one() and notify_all() features too. Note that, std::atomic_flag is a pretty low-level type – you can consider using atomic_bool instead. Also, you can use member functions with the set and the clear methods. You can also use higher level constructs, such as a std::mutex and std:: lock_guard. How to use atomic_flag in modern C++? Here is an atomic_flag C++ example. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34   #include #include #include #include #include   #include   std::atomic_flag flag = ATOMIC_FLAG_INIT;   std::stringstream stream;   void myf(int x) {   while ( flag.test_and_set() ) {}   stream

Read More

Learn Powerful Multi-threading Operations With C++ Builder

Hello C++ developers, multi-thread operations evolved significantly with the advent of C++11, and this continued with additional improvements in the latest standards to enhance multi-thread operations further. The concurrency support library in modern C++ is designed to solve problems that can arise with multi-thread operations. According to the latest news about the new coming C++ Builder 12.0, there might be a new CLANG 15 Win64 compiler and a new Visual Assist in the IDE. This week we have notes about the presentation of “New coming C++ Builder 12.0” along with new posts about multi-thread operations, atomics, data-race problems and how to solve them, bidirectional fences, as well as strong compare and exchange templates. RAD Studio’s C++ Builder, Delphi, and their free community editions C++ Builder CE, and Delphi CE are a real force for modern application development. LearnCPlusPlus.org web page is another powerful element for learning new skills of modern C++ programming. Our educational LearnCPlusPlus.org site has a whole bunch of new and unique posts with examples suitable for everyone from beginners to professionals alike. It is growing well thanks to you, and we have many new readers, thanks to your support! The site features a plethora of posts that are great for learning the features of modern C++ compilers with very simple explanations and examples. Table of Contents Where I can I learn C++ and test these examples with a free C++ compiler? Do you want to know some more news about C++ Builder 12? How can I use atomic operations in C++ Builder? What are atomic operations in C++ and how can I use them? Where I can I learn C++ and test these examples with a free C++ compiler? If you don’t know anything about C++ or the C++ Builder IDE, don’t worry, we have a lot of great examples on the LearnCPlusPlus.org website and they’re all completely free. Just visit this site and copy and paste any examples there into a new Console, VCL, or FMX project, depending on the type of post. We keep adding more C and C++ posts with sample code. In today’s round-up of recent posts on LearnCPlusPlus.org, we have new articles with very simple examples that can be used with: The free version of C++ Builder 11 CE Community Edition or a professional version of C++ Builder  or free BCC32C C++ Compiler and BCC32X C++ Compiler or the free Dev-C++ Read the FAQ notes on the CE license and then simply fill out the form to download C++ Builder 11 CE. Do you want to know some more news about C++ Builder 12? David Millington, Developer and Product Manager of C++ Builder just released a new video about “Behind the Build: RAD Studio and C++Builder 12.0”. According to David Millington’s post, C++ Builder is aiming to include some amazing features and a lot of performance improvements in operations. C++Builder 12 plans to bring some massive improvements, the enhanced Clang toolchain and Visual Assist integration, substantial improvements across RTL, STL, debugging, and more. Here is the full presentation, Here are a few of my notes, Comes with a special CLANG 15 Win64 compiler – Win64 is a primary OS– New Clang means support for C++20 and a lot of C++23 features– Important to have more compatible standards and amazingly faster– In memory allocation operations, it is 6 to 14% faster than the current CLANG Win64 […]

Read More

What Is Weak Compare and Exchange In Modern C++?

Since the C++11 standard, the Concurrency Support Library includes built-in support for threads (std::thread) with atomic operations (std::atomic). C++11 provides both weak and strong compare-and-exchange operations in multi-threading applications. Since C++11, weak compare and exchange are used in modern C++ standards such as C++14, C++17, C++20, and in other new standards. In this post, we explain weak compare and exchange with simple examples. What is weak compare and exchange in C++? The Weak Compare and Exchange template atomically compares the value pointed to by the atomic object with the value pointed to by expected. This feature comes with C++11 and is used in other modern C++ standards. and performs the following operations based on the comparison results: If the comparison result is true (bitwise-equal), the function replaces the value pointed to by the atomic object with the value desired. If the comparison result is false, the function updates the value in expected with the value pointed by the atomic object There are two most common syntaxes for the compare_exchange_weak, first,   bool compare_exchange_weak( T& expected, T desired) noexcept;   and in weak compare and exchange atomic operations, we can use std::compare_exchange_weak template with memory order types. Here is the syntax for the compare_exchange_weak with memory orders,   bool compare_exchange_weak( T& expected, T desired,                               std::memory_order success,                               std::memory_order failure ) noexcept;   here is how we can use it,   std::atomic x;   exchanged = x.compare_exchange_weak( expected, desired);   exchanged = x.compare_exchange_weak( expected, desired, std::memory_order_release, std::memory_order_relaxed);   Note that, providing both compare_exchange_strong and compare_exchange_weak allow us to decide whether we want the library to handle spurious failures (using compare_exchange_strong) or if we want to handle it in our own code (using compare_exchange_weak). The compare_exchange_strong needs extra overhead to retry in the case of failure. For details please see Load-link/store-conditional in Wikipedia. Is there a simple example of weak compare and exchange in C++? Here is a simple example about weak compare and exchange in C++. Let’s assume we have a thread function myf1() that ensures value is changed after a weak compare and exchange. This is how we can do this,   void myf1(int desired) { int expected = 1; bool exchanged;   do { exchanged = x.compare_exchange_weak( expected, desired ); std::cout

Read More

vcpkg 2023.06.20 and 2023.07.21 Releases: GitHub Dependency Graph Support, Android Tested Triplets, Xbox Triplet Improvements, and More…

vcpkg 2023.06.20 and 2023.07.21 Releases: GitHub Dependency Graph Support, Android Tested Triplets, Xbox Triplet Improvements, and More… Augustin Popa July 31st, 20231 3 The 2023.07.21 release of the vcpkg package manager is available. This blog post summarizes changes from April 16th, 2023 to July 21th, 2023 for the Microsoft/vcpkg, Microsoft/vcpkg-tool, and Microsoft/vcpkg-docs GitHub repos. Some stats for this period: 59 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. 976 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,249 total libraries available in the vcpkg public registry. 87 contributors submitted PRs, issues, or participated in discussions in the repo. The main vcpkg repo has over 5,500 forks and 19,300 stars on GitHub.   Notable Changes Notable changes for this release are summarized below:   GitHub Dependency Graph API In June, we announced vcpkg integration with the GitHub dependency graph. This is available for all vcpkg users on the 2023.07.21 release. If you are a GitHub user, we highly recommend checking it out to visualize your repo’s dependencies. We will continue building on this integration in the future and are looking for feedback! PR: Microsoft/vcpkg-tool/#989   Android Tested Triplets We have promoted several Android community triplets to tested triplets. This means they are now tested and validated on all port changes (as of the 2023.06.20 release) and will be listed in the tested triplets table in each release. The new Android tested triplets are: arm-neon-android x64-android arm64-android PR: Microsoft/vcpkg/#29406   Xbox Triplet Improvements In a previous release, community triplets were released for vcpkg users wishing to target Xbox. In this release, several improvements were made to this experience: Added a post build check that libraries don’t link with kernel32, as Xbox does not have kernel32. GameDKLatestis now included in binary cache keys. Xbox triplets require the user of the GameDK, GRDK, and GXDK headers which are supplied through external environment variables. With this change, binary caching will track the version of these dependencies for the purpose of determining when a binary can be restored without re-building. Improvements to triplet selection and turning on the xbox identifier. PR: Microsoft/vcpkg-tool#1059   Updates to depend-info Command vcpkg depend-infodisplays all transitive dependencies for a package in several formats, including plain text, DGML, DOT, etc. This feature can be useful to gain a better understanding of a package’s dependency graph. A user contribution recently added the Mermaid format as an additional option. Furthermore, we made some changes to the way depend-info is used by moving the display options under a common –format subcommand. We believe this layout will make it easier to scale this feature in the future if we add further formatting styles. For more details on how to use depend-info after these changes, see our vcpkg depend-info documentation. PRs: Microsoft/vcpkg-tool/#1080, Microsoft/vcpkg-tool/#935 (thanks @WimLefrere!)   Allow vcpkg remove, export, and x-package-info without overlay triplets In cases where a vcpkg user creates and manages overlay triplets, the commands vcpkg remove, export, and x-package-info can now be run without having to specify those overlay triplets […]

Read More

What’s New for C++ Developers in Visual Studio 2022 17.7

What’s New for C++ Developers in Visual Studio 2022 17.7 Sy Brand August 8th, 20233 2 We are happy to announce that Visual Studio 2022 version 17.7 is now generally available! This post summarizes the new features you can find in this release for C++. You can download Visual Studio 2022 from the Visual Studio downloads page or upgrade your existing installation by following the Update Visual Studio Learn page. Core Editor Comparing Files You no longer need to leave Visual Studio and rely on other tools to compare files. Now you can easily compare any file in Solution Explorer with other files by either: Right-clicking on a single file, selecting “Compare With…” from the context menu which will bring up File Explorer. Navigating to any file on disk and selecting it for comparison. Multi-selecting two files by holding down Ctrl then right-clicking and selecting “Compare Selected” from the context menu. Please share your feedback here.  We’d love to hear your thoughts on this new experience. Copy and Trim Indentation If you have ever copied code from Visual Studio to another application (Outlook, Teams, Slack, etc.) and found that your code indentation has not been copied correctly, you will find that this new capability fixes that for you. Visual Studio now automatically fixes indentation for you when you copy code from Visual Studio and paste it in another application. Parallel Stack Filtering You can use the updated Parallel Stack filtering options that let you selectively display or hide specific threads or frames. This means you can easily concentrate on the threads and frames that are important to you, giving you a clearer picture. Additionally, you can now Drag Select frames from the parallel stack window, allowing you to perform operations like copy/paste, flag/unflag, or freeze/thaw for all the selected frames at once. F5 Speed We have optimized Program Database (PDB) files, resulting in improving debugging sessions and decreasing the project selection screen loading time for Unreal projects for example by 21% (~4 sec gain). Additionally, the F5 path is optimized, leading to a 5-10% improvement in the debugger’s startup time and process launch. All-in-One Search Responsiveness Several accuracy and performance enhancements are coming to All-in-One Search. For example, exact matches now show higher in the results list and results update more accurately in real time as you type your query. Try out the All-In-One Search experience by making sure it is enabled in Tools > Manage Preview Features > “New Visual Studio Search experience (restart required)” and using the Ctrl + T or the Ctrl + Q keyboard shortcut to launch it. If you have feedback to share with us about this feature, let us know here. Find in Files Search Time Find in Files search time has been significantly improved with various optimizations, resulting in a 2x speedup. Game Development C++ Build Insights Thanks to your feedback, we are happy to announce that Build Insights is now integrated with Visual Studio 2022! Build Insights provides you with valuable information needed when optimizing your C++ build times. Start your Build Insights .etl trace capture with a click of a button for your solution or projects. In Visual Studio 17.7, you can now see Included Files and Include Tree view. For advanced profiling, click the “Open in WPA” button to see the trace in Windows Performance Analyzer. After compilation, Build Insights […]

Read More

Learn Multi-threading with Concurrency Support Library in C++

Hello again, as I write this it’s another blazing hot summer week for me, but we don’t let that get in the way of coding and teaching you on our LearnCPlusPlus.org web page. CPUs and GPUs have evolved year on year to feature a greater number of cores and transistors to give more computational power for today’s servers and computers. With the advent of multiple cores, it is common now for programs to make use of multiple simultaneous threads. Multi-threading is one of the great features of modern C++, allowing you to use the maximum number of cores and threads of your CPUs today. For example, the AMD EPYC 9654 with 96 cores 192 threads, or the Intel Xeon w9-3495X 56 cores 112 threads – unimaginable power for anyone looking for CPUs just a decade ago. That power means you can speed up your operations by 2 to 192 times with multi-core CPUs today or you can improve it by 2 or more parallel CPUs.  In modern C++, multi-thread operations are amazingly evolved since C++11, and still there are new improvements in the latest standards to enhance multi-thread operations further. The Concurrency Support Library is designed to solve problems that arise with multi-thread operations and this week we have some examples of multi-threading in C++. This week, we explain what std::thread is and how can we use it with vectors and functors. In multi-threading, concurrency control is important and there is also mutex mutual exclusion and we explain it with very simple, easy to understand examples. We have two more important post picks about the features that come with C++11. The C++11 standard provides an alternative to std::move, which is std::move_if_noexcept and we have examples about it. Unions are rarely used but are another important data type alternative to structs and classes. The C++11 standard loosens up the restriction regarding members of unions, and in the last post, we explain the unrestricted unions feature that came with C++11. Table of Contents Where can I learn C++ with a free C++ compiler? How to use modern C++ with C++ Builder? How to learn C++ for free using C++ Builder? What is new in C++ Builder CE? What might be next for C++ Builder? Where can I learn C++ with a free C++ compiler? If you don’t know anything about C++ or the C++ Builder IDE, don’t worry, we have a lot of great examples on the LearnCPlusPlus.org website and they’re all completely free. Just visit this site and copy and paste any examples there into a new Console, VCL, or FMX project, depending on the type of post. We keep adding more C and C++ posts with sample code. In today’s round-up of recent posts on LearnCPlusPlus.org, we have new articles with very simple examples that can be used with: The free version of C++ Builder 11 CE Community Edition or a professional version of C++ Builder  or free BCC32C C++ Compiler and BCC32X C++ Compiler or the free Dev-C++ Read the FAQ notes on the CE license and then simply fill out the form to download C++ Builder 11 CE. How to use modern C++ with C++ Builder? In C++, vectors are a modern and very flexible form of array in modern C++. Maybe we can say they are like modern linked lists. We can use vectors with std::thread classes for multi-thread operations. In the next […]

Read More