Will C++20 modules change the anatomy of static and shared libraries? - c++

Traditionally, C++ libraries are made of a header file + the implementation compiled in a binary file (.a, .so, .dylib, .dll, ...). The header file is #included in the source code and the binary part is linked to the final executable.
Will modules from C++20 change such layout? If so, will operating systems have to upgrade the way they distribute their core libraries, e.g. the Standard Library in Linux or other core dlls in Windows?

Absolutely. Modules are a very different type of representing library code to users than conventional header/libraries. The main advantage of a module is to have it parsed to the level of the abstract syntax tree (AST) by the compiler. This only happens once per module -- in contrary to every time you include a particular header file. Thus, one possibility for speedup is to convert very frequent header files into modules and save a lot of compiler time in not re-compiling to AST many times, but just once. AST also works perfectly fine for templates ... it is a generic and complete description of the C++ language.
But this is currently also the main "drawback": ASTs are absolutely compiler dependent. There is no stability between vendors, systems, or even compiler versions. So distributing ASTs makes no sense, at least in the current toolchain environment.
Thus, in my understanding, modules are not easily a replacement for common header/libraries. They are a ideal replacement for lightweight (best header-only) and potentially highly templated code to be included many times in typical programs. Many libraries, foremost the standard libraries, are like this. But there are also many libraries of different design (small API+heavy binary backend). For those, I guess, we will have to continue to use include/libraries as before. But, C++ is backward compatible, so mixing modules with includes is no problem at all.
Also, modules can just wrap include files (e.g. with an API). This is probably not a very powerful usage of modules, but may lead to a more uniform programming pattern. In this case, you would still need to link your "so" or "dylib" or whatever library to the resulting code.
Thus, I believe the future at some point will distribute both, some C++ modules, but also conventional headers+libraries. Modules by themselves can be split into many files (only the "exported" symbols are visible to users). Modules will likely follow very different design guidelines than headers. It very likely will not be any advantage to have "one class per module", but rather "a whole bunch of logically connected code per module".

Related

If a library such as iostream is so "standard", why do I have to #include it? Also, how can I look into header files? [duplicate]

This question already has answers here:
Why isn't the C++ standard library already pre-included in any C++ source?
(7 answers)
Closed 1 year ago.
Why must I #include various libraries, such as iostream?
I have learned that libraries, such as iostream specifically, are part of the C++ 'Standard Library' "which are written in the core language and part of the C++ ISO Standard itself."
This is pretty neat, but, if they are so 'standard' and such a 'core part' of the language, why do I need to #include them? Why is it that I can write a script that uses +, -, *, /, or other things without #including any libraries? [As a person completely unqualified to have an opinion on this matter,] I feel like being able to add two operands together is just as essential as being able to retrieve input from an operator (std::cin).
What exactly is the issue? Is it that my specific compiler (using Visual Studio exclusively so far) doesn't have those functions built-in? But the designers chose to innately include simple arithmetic operators instead? I understand the need to do this for an obscure or lesser known library, but not so much iostream.
Secondly, how can I 'look inside' a standard header file, such as iostream? How can I inspect the source code of common header files to see how string compare or cin works? I understand the beauty of abstraction and not having to know the nitty gritty details, but I'm obsessed with knowing how everything works.
Third, are there penalties associated with #including header files? For example, if I #include iostream, but I only use a single operator, such as std::cin, is the entire header file included in the final product? Would my program/file or the machine running it be burdened with the unused portions of iostream?
When looking at a C++ "implementation", you are really looking at two separate parts: The compiler, and the library. Basics like integer arithmetics, pointers, references and the like are defined by the core language, and implemented in the compiler core.
Higher level functions are defined in libraries. Of these, the Standard Library is only one, and defined in the same standard document as the language core.
But the standard library can be, and often is, a separate project that only happens to work in tandem with the compiler. You might use the compiler with a different library implementation, or may use the library implementation with a different compiler.
That you have to #include headers before you can use the library has something to do with efficiency. Both the compiler and you (or any other developer reading your source later on) only has to "know" about those parts of any libraries that are actually #included by your source. The compiler has less looking-up to do when parsing your code, and a developer knows pretty exactly which part of the documentation to look at for further information -- especially if you resist the urge to write using namespace ... in your source. This becomes even more important later on when you will be using several different libraries with different namespaces.
You should not use the header files for information. Highly abstracted C++ source can be somewhat of a handful to understand, and the headers are usually not written for the end user anyway. You are very much better off by referring to actual documentation, like cppreference.com, instead.
As for the third part of your question, including a header will introduce all the identifiers from that header (and, with C++, likely several other headers as well) into your translation unit. (With C, the library implementation is actually forbidden to introduce any identifiers from other standard headers unless that header was explicitly included.) This should not bother you, though. Things that are not needed do not result in actual code in your resulting binary. With really small example programs and <iostream> specifically, the "burden" might seem comparatively large because something "simple" like std::cin requires significant support (files, streams, buffers and the like). But this effect rapidly diminishes as your program becomes larger, because whatever support code is added to your binary is only added once.
And finally, most of the above is the same in other languages as well, with only minor differences. Java, C# or Python might not have "headers" per se, but in the end the issues with the standard library being separate from the compiler, identifier namespacing, and (as far as compiled languages are concerned) effect on resulting binary are similar across the board.

Are header files same or different for multiple platforms?

When ever we create a header file for a dll or some library.It mite have platform specific code.So generally are header files distributed according to platforms?(Linux,Mac,Windows)
What about the header files of boost libraries or wxwidgets libraries?
When creating a library, you are generally best off when header files are identical for all platforms. However, for most practical libraries there are some system dependencies which mandate differences. Users of a library are best isolated from any differences to start with and it may be reasonable to encapsulate the platform specifics into the implementation, e.g., using the Private Implementation idiom.
Where system dependencies creep into the interface there may be variation in declarations in the header. For example, the way networking infrastructure is accessed is system dependent and the involved types and function calls differ between platforms. If the data structures are embedded directly into a user-visible class (e.g., improve performance) or functions are called from a header, e.g., because they are called from a function template, there may be differences.
My preference on dealing with differences in headers is to use conditional compilation and keep the same header and interface. In most cases I try to further centralize the use of conditional compilation to one location for each entity different to avoid conditional compilation as much as possible: when another configuration becomes necessary, I want to update as few places as possible.
Ideally implementation of interfaces in header file should be different as per platforms (Linux,Mac,Windows) .In a standard implementation , header file should be same .
Code for different platforms is separated using compilation flag .
Thats the ideal case , however some poor library may have even different headers.

Share Fortran library without revealing source code

I have a software developed in-house. It is written in Fortran and consists of 3 kinds of files: 1) the solver files, 2) the models' files and 3) a file where the models used are defined. The solver also uses some libraries namely lapack and HSL ma41. Usually, I select the needed models for the user, compile all together and provide an executable.
I want to allow users to add their own models or modify the existing ones without being able to change/modify/see the solver source code.
One thought was to compile the solver into an object file. Then the user would compile the definition file and his models and link them together with the libraries. Is that possible? I guess then the user must have the same platform as the one the solver was compiled on? (ie Intel compiler on Windows 64-bit) So I'll need to built a library for any possible combination OS/hardware/compiler?
Another idea is to send the solver source also but use obfuscation. I can't find any tested/reliable solutions for that online? Is it a good option?
Thanks in advance.
You can distribute the object code in a library, as you propose. If the entry points for your code are in Fortran modules, then you also need to distribute the mod files (or equivalent for your compiler) that also result from compilation of the modules.
(If any of the entry points for your library code are external procedures then it is a convenience for your users if you provide interface blocks for those external procedures. These interface blocks can be in source form (the interface block contains no information beyond what your library's documentation would have to provide), or again could be pre-compiled into a module.)
Object code may be platform (architecture) specific, compiler specific, compiler version specific and in some cases compile options specific. Careful design and specification of the interface between your solver and the clients models can mitigate some of the potential variation. For example - many platforms have a well defined (perhaps through explicit specification or near ubiquitous convention) C application binary interface, so interfaces described using the C equivalent are typically robust, at the cost of significant loss of capability over a common-processor Fortran to Fortran interface.

C++ internal code reuse: compile everything or share the library / dynamic library?

General question:
For unmanaged C++, what's better for internal code sharing?
Reuse code by sharing the actual source code? OR
Reuse code by sharing the library / dynamic library (+ all the header files)
Whichever it is: what's your strategy for reducing duplicate code (copy-paste syndrome), code bloat?
Specific example:
Here's how we share the code in my organization:
We reuse code by sharing the actual source code.
We develop on Windows using VS2008, though our project actually needs to be cross-platform. We have many projects (.vcproj) committed to the repository; some might have its own repository, some might be part of a repository. For each deliverable solution (.sln) (e.g. something that we deliver to the customer), it will svn:externals all the necessary projects (.vcproj) from the repository to assemble the "final" product.
This works fine, but I'm quite worried about eventually the code size for each solution could get quite huge (right now our total code size is about 75K SLOC).
Also one thing to note is that we prevent all transitive dependency. That is, each project (.vcproj) that is not an actual solution (.sln) is not allowed to svn:externals any other project even if it depends on it. This is because you could have 2 projects (.vcproj) that might depend on the same library (i.e. Boost) or project (.vcproj), thus when you svn:externals both projects into a single solution, svn:externals will do it twice. So we carefully document all dependencies for each project, and it's up to guy that creates the solution (.sln) to ensure all dependencies (including transitive) are svn:externals as part of the solution.
If we reuse code by using .lib , .dll instead, this would obviously reduce the code size for each solution, as well as eliminiate the transitive dependency mentioned above where applicable (exceptions are, for example, third-party library/framework that use dll like Intel TBB and the default Qt)
Addendum: (read if you wish)
Another motivation to share source code might be summed up best by Dr. GUI:
On top of that, what C++ makes easy is
not creation of reusable binary
components; rather, C++ makes it
relatively easy to reuse source code.
Note that most major C++ libraries are
shipped in source form, not compiled
form. It's all too often necessary to
look at that source in order to
inherit correctly from an object—and
it's all too easy (and often
necessary) to rely on implementation
details of the original library when
you reuse it. As if that isn't bad
enough, it's often tempting (or
necessary) to modify the original
source and do a private build of the
library. (How many private builds of
MFC are there? The world will never
know . . .)
Maybe this is why when you look at libraries like Intel Math Kernel library, in their "lib" folder, they have "vc7", "vc8", "vc9" for each of the Visual Studio version. Scary stuff.
Or how about this assertion:
C++ is notoriously non-accommodating
when it comes to plugins. C++ is
extremely platform-specific and
compiler-specific. The C++ standard
doesn't specify an Application Binary
Interface (ABI), which means that C++
libraries from different compilers or
even different versions of the same
compiler are incompatible. Add to that
the fact that C++ has no concept of
dynamic loading and each platform
provide its own solution (incompatible
with others) and you get the picture.
What's your thoughts on the above assertion? Does something like Java or .NET face these kinds of problems? e.g. if I produce a JAR file from Netbeans, will it work if I import it into IntelliJ as long as I ensure that both have compatible JRE/JDK?
People seem to think that C specifies an ABI. It doesn't, and I'm not aware of any standardised compiled language that does. To answer your main question, use of libraries is of course the way to go - I can't imagine doing anything else.
One good reason to share the source code: Templates are one of C++'s best features because they are an elegant way around the rigidity of static typing, but by their nature are a source-level construct. If you focus on binary-level interfaces instead of source-level interfaces, your use of templates will be limited.
We do the same. Trying to use binaries can be a real problem if you need to use shared code on different platforms, build environments, or even if you need different build options such as static vs. dynamic linking to the C runtime, different structure packing settings, etc..
I typically set projects up to build as much from source on-demand as possible, even with third-party code such as zlib and libpng. For those things that must be built separately, e.g. Boost, I typically have to build 4 or 8 different sets of binaries for the various combinations of settings needed (debug/release, VS7.1/VS9, static/dynamic), and manage the binaries along with the debugging information files in source control.
Of course, if everyone sharing your code is using the same tools on the same platform with the same options, then it's a different story.
I never saw shared libraries as a way to reuse code from an old project into a new one. I always thought it was more about sharing a library between different applications that you're developing at about the same time, to minimize bloat.
As far as copy-paste syndrome goes, if I copy and paste it in more than a couple places, it needs to be its own function. That's independent of whether the library is shared or not.
When we reuse code from an old project, we always bring it in as source. There's always something that needs tweaking, and its usually safer to tweak a project-specific version than to tweak a shared version that can wind up breaking the previous project. Going back and fixing the previous project is out of the question because 1) it worked (and shipped) already, 2) it's no longer funded, and 3) the test hardware needed may no longer be available.
For example, we had a communication library that had an API for sending a "message", a block of data with a message ID, over a socket, pipe, whatever:
void Foo:Send(unsigned messageID, const void* buffer, size_t bufSize);
But in a later project, we needed an optimization: the message needed to consist of several blocks of data in different parts of memory concatenated together, and we couldn't (and didn't want to, anyway) do the pointer math to create the data in its "assembled" form in the first place, and the process of copying the parts together into a unified buffer was taking too long. So we added a new API:
void Foo:SendMultiple(unsigned messageID, const void** buffer, size_t* bufSize);
Which would assemble the buffers into a message and send it. (The base class's method allocated a temporary buffer, copied the parts together, and called Foo::Send(); subclasses could use this as a default or override it with their own, e.g. the class that sent the message on a socket would just call send() for each buffer, eliminating a lot of copies.)
Now, by doing this, we have the option of backporting (copying, really) the changes to the older version, but we're not required to backport. This gives the managers flexibility, based on the time and funding constraints they have.
EDIT: After reading Neil's comment, I thought of something that we do that I need to clarify.
In our code, we do lots of "libraries". LOTS of them. One big program I wrote had something like 50 of them. Because, for us and with our build setup, they're easy.
We use a tool that auto-generates makefiles on the fly, taking care of dependencies and almost everything. If there's anything strange that needs to be done, we write a file with the exceptions, usually just a few lines.
It works like this: The tool finds everything in the directory that looks like a source file, generates dependencies if the file changed, and spits out the needed rules. Then it makes a rule to take eveything and ar/ranlib it into a libxxx.a file, named after the directory. All the objects and library are put in a subdirectory that is named after the target platform (this makes cross-compilation easy to support). This process is then repeated for every subdirectory (except the object file subdirs). Then the top-level directory gets linked with all the subdirs' libraries into the executable, and a symlink is created, again, naked after the top-level directory.
So directories are libraries. To use a library in a program, make a symbolic link to it. Painless. Ergo, everything's partitioned into libraries from the outset. If you want a shared lib, you put a ".so" suffix on the directory name.
To pull in a library from another project, I just use a Subversion external to fetch the needed directories. The symlinks are relative, so as long as I don't leave something behind it still works. When we ship, we lock the external reference to a specific revision of the parent.
If we need to add functionality to a library, we can do one of several things. We can revise the parent (if it's still an active project and thus testable), tell Subversion to use the newer revision and fix any bugs that pop up. Or we can just clone the code, replacing the external link, if messing with the parent is too risky. Either way, it still looks like a "library" to us, but I'm not sure that it matches the spirit of a library.
We're in the process of moving to Mercurial, which has no "externals" mechanism so we have to either clone the libraries in the first place, use rsync to keep the code synced between the different repositories, or force a common directory structure so you can have hg pull from multiple parents. The last option seems to be working pretty well.

Where do I learn "what I need to know" about C++ compilers?

I'm just starting to explore C++, so forgive the newbiness of this question. I also beg your indulgence on how open ended this question is. I think it could be broken down, but I think that this information belongs in the same place.
(FYI -- I am working predominantly with the QT SDK and mingw32-make right now and I seem to have configured them correctly for my machine.)
I knew that there was a lot in the language which is compiler-driven -- I've heard about pre-compiler directives, but it seems like someone would be able to write books the different C++ compilers and their respective parameters. In addition, there are commands which apparently precede make (like qmake, for example (is this something only in QT)).
I would like to know if there is any place which gives me an overview of what compilers are out there, and what their different options are. I'd also like to know how each of them views Makefiles (it seems that there is a difference in syntax between them?).
If there is no website regarding, "Everything you need to know about C++ compilers but were afraid to ask," what would be the best way to go about learning the answers to these questions?
Concerning the "numerous options of the various compilers"
A piece of good news: you needn't worry about the detail of most of these options. You will, in due time, delve into this, only for the very compiler you use, and maybe only for the options that pertain to a particular set of features. But as a novice, generally trust the default options or the ones supplied with the make files.
The broad categories of these features (and I may be missing a few) are:
pre-processor defines (now, you may need a few of these)
code generation (target CPU, FPU usage...)
optimization (hints for the compiler to favor speed over size and such)
inclusion of debug info (which is extra data left in the object/binary and which enables the debugger to know where each line of code starts, what the variables names are etc.)
directives for the linker
output type (exe, library, memory maps...)
C/C++ language compliance and warnings (compatibility with previous version of the compiler, compliance to current and past C Standards, warning about common possible bug-indicative patterns...)
compile-time verbosity and help
Concerning an inventory of compilers with their options and features
I know of no such list but I'm sure it probably exists on the web. However, suggest that, as a novice you worry little about these "details", and use whatever free compiler you can find (gcc certainly a great choice), and build experience with the language and the build process. C professionals may likely argue, with good reason and at length on the merits of various compilers and associated runtine etc., but for generic purposes -and then some- the free stuff is all that is needed.
Concerning the build process
The most trivial applications, such these made of a single unit of compilation (read a single C/C++ source file), can be built with a simple batch file where the various compiler and linker options are hardcoded, and where the name of file is specified on the command line.
For all other cases, it is very important to codify the build process so that it can be done
a) automatically and
b) reliably, i.e. with repeatability.
The "recipe" associated with this build process is often encapsulated in a make file or as the complexity grows, possibly several make files, possibly "bundled together in a script/bat file.
This (make file syntax) you need to get familiar with, even if you use alternatives to make/nmake, such as Apache Ant; the reason is that many (most?) source code packages include a make file.
In a nutshell, make files are text files and they allow defining targets, and the associated command to build a target. Each target is associated with its dependencies, which allows the make logic to decide what targets are out of date and should be rebuilt, and, before rebuilding them, what possibly dependencies should also be rebuilt. That way, when you modify say an include file (and if the make file is properly configured) any c file that used this header will be recompiled and any binary which links with the corresponding obj file will be rebuilt as well. make also include options to force all targets to be rebuilt, and this is sometimes handy to be sure that you truly have a current built (for example in the case some dependencies of a given object are not declared in the make).
On the Pre-processor:
The pre-processor is the first step toward compiling, although it is technically not part of the compilation. The purposes of this step are:
to remove any comment, and extraneous whitespace
to substitute any macro reference with the relevant C/C++ syntax. Some macros for example are used to define constant values such as say some email address used in the program; during per-processing any reference to this constant value (btw by convention such constants are named with ALL_CAPS_AND_UNDERSCORES) is replace by the actual C string literal containing the email address.
to exclude all conditional compiling branches that are not relevant (the #IFDEF and the like)
What's important to know about the pre-processor is that the pre-processor directive are NOT part of the C-Language proper, and they serve several important functions such as the conditional compiling mentionned earlier (used for example to have multiple versions of the program, say for different Operating Systems, or indeed for different compilers)
Taking it from there...
After this manifesto of mine... I encourage to read but little more, and to dive into programming and building binaries. It is a very good idea to try and get a broad picture of the framework etc. but this can be overdone, a bit akin to the exchange student who stays in his/her room reading the Webster dictionary to be "prepared" for meeting native speakers, rather than just "doing it!".
Ideally you shouldn't need to care what C++ compiler you are using. The compatability to the standard has got much better in recent years (even from microsoft)
Compiler flags obviously differ but the same features are generally available, it's just a differently named option to eg. set warning level on GCC and ms-cl
The build system is indepenant of the compiler, you can use any make with any compiler.
That is a lot of questions in one.
C++ compilers are a lot like hammers: They come in all sizes and shapes, with different abilities and features, intended for different types of users, and at different price points; ultimately they all are for doing the same basic task as the others.
Some are intended for highly specialized applications, like high-performance graphics, and have numerous extensions and libraries to assist the engineer with those types of problems. Others are meant for general purpose use, and aren't necessarily always the greatest for extreme work.
The technique for using each type of hammer varies from model to model—and version to version—but they all have a lot in common. The macro preprocessor is a standard part of C and C++ compilers.
A brief comparison of many C++ compilers is here. Also check out the list of C compilers, since many programs don't use any C++ features and can be compiled by ordinary C.
C++ compilers don't "view" makefiles. The rules of a makefile may invoke a C++ compiler, but also may "compile" assembly language modules (assembling), process other languages, build libraries, link modules, and/or post-process object modules. Makefiles often contain rules for cleaning up intermediate files, establishing debug environments, obtaining source code, etc., etc. Compilation is one link in a long chain of steps to develop software.
Also, many development environments abstract the makefile into a "project file" which is used by an integrated development environment (IDE) in an attempt to simplify or automate many programming tasks. See a comparison here.
As for learning: choose a specific problem to solve and dive in. The target platform (Linux/Windows/etc.) and problem space will narrow the choices pretty well. Which you choose is often linked to other considerations, such as working for a particular company, or being part of a team. C++ has something like 95% commonality among all its flavors. Learn any one of them well, and learning the next is a piece of cake.