Is g++ both a c++ compiler and a linker? - c++

I was looking at the output from my build in Eclipse. I'm cross compiling for a ColdFire processor. The compilation line looks like this:
m68k-elf-g++ -O2 -falign-functions=4 -IC:\nburn\include -IC:\nburn\MOD52...
followed by more include file, obvious "compiler" flags and finally the one source file I changed. The next line invokes the same tool again:
m68k-elf-g++ src\main.o src\TouchPanelMediator.o src\Startup.o....
followed by more .o files some .ld files and some .a files. This appears to be linking all the various types of object files together.
In the Gnu family is g++ some uber application that can determine based on arguments whether it needs to compile or link? Does it have both capabilities built-in or is it just dispatching compiling to gcc and linking to ld and my log just doesn't show that?

g++ and gcc are drivers. Usually, they run the preprocessor (cpp), compiler proper (cc1plus for C++ and cc1 for C) and the linker (gold or GNU ld) and all other things necessary. The difference between gcc and g++ is that the latter includes one additional library to link against (libstdc++).
Depending on what type of file they are invoked on, they may omit some steps or do things differently. For .o files, it doesn't need to run the compiler proper or the preprocessor, for example.
If you pass -### to them, you can see it print the tools it invokes in each step of its execution.

Taken from this little GCC guide:
Based on the file extension that you gave your program, it selects the appropriate commands it needs to run to turn the source you gave it into the output file you specified.
With a nice little flowchart of what GCC exactly does, depending on the file extensions:
input extensions runs if output

It dispatches linking to ld.
Also see here:
How to get GCC linker command?

Related

In C or C++, does the compiler do implicit linking?

How does some std-lib, external-libs or any other pre-compiled src code such as the well-known header file <iostream> with its corresponding object file or static/dll lib get linked into my own application automatically? Does the compiler do it implicitly/under-the-hood or something like a compiler pre-linked list operation?
If such a case exist how do we use its functionality in our accord, Is there a way to put my own obj, dll, static-lib or src file into that ideal list via writing some special syntax without changing the initial directories of each of it, neither the help of an IDE config and outside-software, the goal is to drop the linking phase explicitly at terminal, want to do this configuration inside of the src-code.
Does every std-lib had a direct/inline special src-code that doing this kind of operation? If there are, then how do we take advantage of it? Or if everything is done by a compiler/handler and if it is generic-type then you could modified it with less problem but the delema is, it is fixed with the compiler and hate to forcefully modified/forked it. If there is alreadly a way to do this without explicitly tinkering it, for such doing it only at your onw src-code/write-time as a said at the first line of this block statement: "Does every std-lib/external-lib had a direct/inline special src-code that doing this kind of operation?".
// a.cpp
#include<iostream>
// there's no linking on iostream obj, src, dll, static-lib file
// love to have this kind of special features to our own none-std-lib/etc.
>c/cpp-compiler -c a.cpp
>c/cpp-compiler -o a a.o
Note: some of my terminologies are base on my own experience so watch out and be open-minded. For as I grow in the coding-community using terminology/standard way of communicating are a mess specially exploring from low to another low and to high to another high level prog-lang.
It depends on what you call "the compiler".
Most modern toolchains - including gcc, clang, Visual C++ - are based on a "compile then link" model, with several components. One of those components is the preprocessor (which does text substitution on C or C++ source code, to produce some modified source code), a "compiler" that translates preprocessed source code into object files, utility programs that produce libraries from sets of source files, a linker that produces an executable file from a set of object files and libraries, and - last but by no means least - a driver program that coordinates execution of other components.
The specifics are different between toolchains - e.g. VC++ does things quite differently than gcc/g++ or clang. The concepts are similar.
In what follows, I'll give a very over-simplistic (imprecise, details omitted) discussion of what gcc and g++ (in the gnu compiler collection) do.
When you use gcc or g++ at the command line you're actually using a driver program, that orchestrates execution of a bunch of other programs (the preprocessor, the compiler, the linker, etc). Depending on what options you provide, the result produced differs. For example, gcc -E only completes preprocessing of source files, g++ -c means the process stops after compiling source files to produce object files. If used to produce an executable, the driver program will use the linker to (well!) link object files and libraries together to produce an executable.
So, if you think of gcc or g++ (the program you execute directly) as the compiler then you could claim the compiler does implicit linking. When being used to create an executable, both execute the linker - and provide it information needed (e.g. names of libraries). gcc automatically links in libraries needed by C programs (e.g. the C standard library) while g++ automatically links in libraries needed by C++ programs (e.g. parts of the C++ standard library as well as the C standard library).
However, if you take a narrower view of the compiler - it is the program that only translates source files into object files - then there is no implicit linking of libraries by the compiler. It is the driver program that orchestrates compiling and linking, not the compiler that orchestrates linking.
If you read documentation for your favourite toolchain, it will describe various means (extensions of source files, settings, command line options, values of environment variables, etc) to control what it does. There is typically flexibility to do preprocessing only, compilation only, output assembler, linking only, or a complete "compile multiple source files then link them together to produce an executable" process.
The linker search libraries in some oreder in which the standard libs folder is searched first.
There are somed default libraries that gets loaded by default like glibc.
this way you dont need to specify to the linker to link with standard libs.
Gcc even have flags for not linking with some standard libs
https://docs.oracle.com/cd/E19205-01/819-5262/auto29/index.html
Note that while it is not standard Microsoft's Visual C++ has a #pragma based language extension that allows specifying files to link in the source:
#pragma comment(lib, "yourfile.lib") // or yourfile.obj
The comment pragma can also be used to specify a few other linker command line options, for example:
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='' publicKeyToken='6595b64144ccf1df' language=''"")
Note that the list of linker options that can be specified this way is fairly limited and that while there are a few other legal 'comment' types only lib and linker really have meaning.
In C or C++, does the compiler do implicit linking?
As the "compiler" (understood as the whole group of tools in the chain that generate the final executable) has whole control over creating that final executable, it does everything related to every stage of compilation, including implicit linking.
How does some std-lib, external-libs or any other pre-compiled src code such as the well-known header file with its corresponding object file or static/dll lib get linked into my own application automatically?
The same as any other library is linked - linker searches the library for symbols and uses them.
Does the compiler do it implicitly/under-the-hood or something like a compiler pre-linked list operation?
Yes (for the compilers I worked with).
But it's very specific to the compiler. From the point of C++ language, there is no requirement on compiler command line options. If the compiler -needs-this-option-to-link-with-standard-library, it's fine and specific to that compiler. It's a quality of implementation issue. Surely users would want some things to be done implicitly with sane defaults for that compiler.
how do we use its functionality in our accord, Is there a way to put my own obj/dll/static-lib/src file into that ideal list via writing some special syntax without changing the initial directories of each of i
Because the compiler does it implicitly, you have to modify the compiler. That strongly depends on the compiler, and specific system and specific compiler own very specific configuration and build settings.
For example on Linux with gcc you can use the method in Enable AddressSanitizer by default in gcc . You can also use the method in Custom gcc preprocessor but overwrite collect2 stage.

G++ compiler giving "undefined reference" error to functions I have clearly defined

I have referenced several other questions on this site and others addressing this topic and nothing has helped my issue so far.
I have two classes and a main program written in c++. Total 5 files. Everything is written originally in Visual Studio 2013 and compiles and runs there.
All are in a single folder and I use this command to compile them:
g++ myprogram.cpp
I get errors "undefined reference" errors for the contructors and destructors of both classes. Is there something obvious that I am doing wrong? If not I will post my code. Thank you.
When you invoke g++ directly like this, it will do all the steps by default, including linking. Since you haven't listed your other source files, you really just want to do compilation (it would seem) and then link the results of compiling each individual source file. You can use the "-c" option to make it just compile (rather than compile and link). Or, if you do want to build all your source files and link them together, then you should list all of the source files in question. That is:
g++ *.cpp -o yourexecutable # To compile and link all the sources
Or:
g++ -c yourfile.cpp -o yourobjectfile.o # To compile a single source
But really you shouldn't invoke g++ directly at all; there are build systems that provide a layer of abstraction on top of GCC (and other tool chains) that would be a far better, more portable, and simpler approach to building your application. For example, Bazel or Gradle would be better ways to build your program from the commandline. Though not the best or most modern build system, even using Make (and relying on its implicit rules) would be better than direclty invoking the compiler.

How to get clang to link against a library without the "lib" prefix?

My situation is I have a library that doesn't have a "lib" prefix. I'd like to link against it, and I can't recompile it (it's actually a Python module).
Now, if you use the '-l' flag with GCC or clang, then the lib prefix is automatically added and the library is not found. For GCC, I can use '-l:mylib.so' to get it to link against an arbitrary file.
However, this doesn't work for clang. Is it possible to get clang to link against a particular library without the 'lib' prefix?
This answers the question, but from a somewhat different angle. See the related question C++ 11 code compiles with `clang++`, but not with `clang -x c++`.
The gcc documention states:
Object files are distinguished from libraries by the linker according to the file contents.
This does not work if you use clang++ -x c++. Instead, the library file is taken as a C++ source file, and this generates a million or so compile errors. And you can't put the library file before the -x c++, because the needed symbols won't be linked in.
One obvious solution is to rename your source files to have a .cpp extension, so the -x switch is unnecessary (or use symbolic links). But this might be a pain to add to your build system.
Another solution, directly related to the OP's question, is to specify the library via the flags:
-L. -l:mylib.foo
If the library is not in the local directory, change the dot . accordingly.

CURL is in /usr/include but still won't automatically be found by g++

Every time I want to use CURL in one of my C++ programs, I have to add the flag -lcurl as a flag onto g++. This can be especially annoying when working with Eclipse. If /usr/include/curl/curl.h exists, what do I need to do to have CURL always be within the include path for g++?
tl;dr: you have to add the flag.
The linker needs libcurl, not the compiler. The compiler needs the header; the linker needs the lib.
To simplify things quite a bit, the header file tells the compiler that the declarations will be defined later. libcurl is what actually defines them.
The linker does not guess-and-check what to link against (doing so would be a horrible idea). You must explicitly tell it what to link against (except for the default libs). In particular, the linker has to know to use libcurl to find the declarations that curl.h laid out. Without libcurl, the linker is missing functions and thus cannot produce a complete binary.
I'm not familiar with Eclipse, but I'm nearly positive that it has an option where you can specify additional libraries. Yes, you'll have to do that once per project, but that shouldn't be a major overhead.
Try adding curl path in
Properties -> C/C++ General -> Paths and Symbols:
This is just how linking works in C and C++.
When you compile the program, you include the header file /usr/include/curl/curl.h. The compiler does this part. The header file contains all of the definitions for the library interface.
When you link the program, you link in the library /usr/lib/libcurl.so, or whatever it happens to be named. The linker does this part. The library contains the implementation in either a loadable (for dynamic libraries) or linkable (for static libraries) format.
The C and C++ languages have no way of specifying which libraries should be linked in, so you have to pass -lcurl to the linker. This is just the way it is.
There are some extensions to C and C++ that allow you to encode library dependencies in your source code, e.g., #pragma comment with MSC, but they're not supported by your typical ELF toolchain, as far as I know.
Note: Actually, the -lcurl flag is not for g++, but it is for the linker, ld. When you pass -lcurl to g++, g++ passes it through to the linker.

Minimal executable size after linkage

I link with Qt statically, so can linker or some other tool avoid adding unused binary code (from Qt libraries) to the final executable? I don't think i use all the 10 MB of Qt library code.
If you compile the Qt library yourself at some point and you are using the g++ you should try to use the Link Time Optimisation (LTO) options.
You can do this by adding -flto to all your g++ calls. This lets the g++ add so called GIMPLE code to your object files which corresponds to your source (so it is not completly compiled). In the linking step you should add -fwhole-program or -fuse-linker-plugin. The gcc then reads the Gimple code, and optimises your program as a whole, therby it should be able to get rid of any unused code. However I cannot garantee this works for you.