Compiling a C++ program with GCC - c++

How can I compile a C++ program with the GCC compiler?
File info.c
#include<iostream>
using std::cout;
using std::endl;
int main()
{
#ifdef __cplusplus
cout << "C++ compiler in use and version is " << __cplusplus << endl;
#endif
cout <<"Version is " << __STDC_VERSION__ << endl;
cout << "Hi" << __FILE__ << __LINE__ << endl;
}
And when I try to compile info.c:
gcc info.C
Undefined first referenced
symbol in file
cout /var/tmp/ccPxLN2a.o
endl(ostream &) /var/tmp/ccPxLN2a.o
ostream::operator<<(ostream &(*)(ostream &))/var/tmp/ccPxLN2a.o
ostream::operator<<(int) /var/tmp/ccPxLN2a.o
ostream::operator<<(long) /var/tmp/ccPxLN2a.o
ostream::operator<<(char const *) /var/tmp/ccPxLN2a.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
Isn't the GCC compiler capable of compiling C++ programs?
On a related note, what is the difference between gcc and g++?

gcc can actually compile C++ code just fine. The errors you received are linker errors, not compiler errors.
Odds are that if you change the compilation line to be this:
gcc info.C -lstdc++
which makes it link to the standard C++ library, then it will work just fine.
However, you should just make your life easier and use g++.
Rup says it best in his comment to another answer:
[...] gcc will
select the correct back-end compiler
based on file extension (i.e. will
compile a .c as C and a .cc as C++)
and links binaries against just the
standard C and GCC helper libraries by
default regardless of input languages;
g++ will also select the correct
back-end based on extension except
that I think it compiles all C source
as C++ instead (i.e. it compiles both
.c and .cc as C++) and it includes
libstdc++ in its link step regardless
of input languages.

If you give the code a .c extension the compiler thinks it is C code, not C++. And the C++ compiler driver is called g++, if you use the gcc driver you will have linker problems, as the standard C++ libraries will not be linked by default. So you want:
g++ myprog.cpp
And do not even consider using an uppercase .C extension, unless you never want to port your code, and are prepared to be hated by those you work with.

You should use g++ instead of gcc.

By default, gcc selects the language based on the file extension, but you can force gcc to select a different language backend with the -x option thus:
gcc -x c++
More options are detailed on the gcc man page under "Options controlling the kind of output". See e.g. gcc(1) - Linux man page (search on the page for the text -x language).
This facility is very useful in cases where gcc can't guess the language using a file extension, for example if you're generating code and feeding it to gcc via standard input.

The difference between gcc and g++ are:
gcc | g++
compiles C source | compiles C++ source
Use g++ instead of gcc to compile you C++ source.

If I recall correctly, gcc determines the filetype from the suffix. So, make it foo.cc and it should work.
And, to answer your other question, that is the difference between "gcc" and "g++". gcc is a frontend that chooses the correct compiler.

An update with my GCC version 10.3.0 on Ubuntu. Even if I add -lstdc++ or use the correct extension, cc1plus must be installed on the system. Otherwise this error shows up:
gcc: fatal error: cannot execute ‘cc1plus’: execvp: No such file or directory
One way to get this is to install g++ even if you're not going to use it directly, e.g. sudo apt install g++.
Now, if I use the extension .cc, I can just call gcc directly, however, warnings and errors still show up. To use gcc cleanly, with a .c extension I have to call it like this:
gcc -x c++ info.c -lstdc++
Shorter if I use the .cc extension, like the accepted answer:
gcc info.cc -lstdc++
Or like others have said, just use g++ info.c instead. No extra parameters are needed to indicate C++, and it works with .c, .cc and .cpp extensions.

It worked well for me. Just one line code on the Windows command line (CMD).
First, confirm that you have installed gcc (for C) or g++ (for C++) compiler.
On the command line, for gcc, type:
gcc --version
On the command line, for g++, type:
g++ --version
If it is installed then proceed.
Now, compile your .c or .cpp using the command line.
For C syntax:
gcc -o exe_filename yourfilename.c
Example:
gcc -o myfile myfile.c
Here exe_filename (myfile in example) is the name of your .exe file which you want to produce after compilation (Note: I have not put any extension here). And yourfilename.c (myfile.c in example) is the your source file which has the .c extension.
Now go to the folder containing your .c file. Here you will find a file with the .exe extension. Just open it. Hurray...
For C++ syntax:
g++ -o exe_filename yourfilename.cpp
After it, the process is the same as for the C syntax.

For a .cpp File:
g++ myprog.cpp -o myprog

Related

Do I still have to link -std=c++11? [duplicate]

I have a piece of code that looks like the following. Let's say it's in a file named example.cpp
#include <fstream>
#include <string> // line added after edit for clarity
int main() {
std::string filename = "input.txt";
std::ifstream in(filename);
return 0;
}
On a windows, if I type in the cmd the command g++ example.cpp, it will fail. It's a long list of errors I think mostly due to the linker complaining about not being able to convert from string to const char*.
But if I run the compiler using an additional argument like so: g++ -std=c++17 example.cpp, it will compile and work fine with no problems.
What happens when I run the former command? I'm guessing a default version standard of the C++ compiler gets called, but I don't know which? And as a programmer/developer, should I always use the latter command with the extra argument?
If your version of g++ is later than 4.7 I think you can find the default version of C++ standard supported like so:
g++ -dM -E -x c++ /dev/null | grep -F __cplusplus
An example from my machine:
mburr#mint17 ~ $ g++ --version | head -1
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
mburr#mint17 ~ $ g++ -dM -E -x c++ /dev/null | grep -F __cplusplus
#define __cplusplus 199711L
Some references:
Details on the g++ options used
Why this only works for g++ 4.7 or later
g++ man page actually tells what is the default standard for C++ code.
Use following script to show the relevant part:
man g++ | col -b | grep -B 2 -e '-std=.* This is the default'
For example, in RHEL 6 g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-23), the output:
gnu++98
GNU dialect of -std=c++98. This is the default for C++ code.
And in Fedora 28 g++ (GCC) 8.1.1 20180502 (Red Hat 8.1.1-1), the output:
gnu++14
gnu++1y
GNU dialect of -std=c++14. This is the default for C++ code. The name gnu++1y is deprecated.
You can also check with gdb
$ g++ example.cpp -g Compile program with -g flag to generate debug info
$ gdb a.out Debug program with gdb
(gdb) b main Put a breakpoint at main
(gdb) run Run program (will pause at breakpoint)
(gdb) info source
Prints out something like:
Current source file is example.cpp
Compilation directory is /home/xxx/cpp
Located in /home/xxx/cpp/example.cpp
Contains 7 lines.
Source language is c++.
Producer is GNU C++14 6.3.0 20170516 -mtune=generic -march=x86-64 -g.
Compiled with DWARF 2 debugging format.
Does not include preprocessor macro info.
There is the standard used by compiler: Producer is GNU C++14
If you recompile your program using -std=c++11 (for example), gdb detects it:
Producer is GNU C++11
I believe that it is possible to tell by looking at the man page (at least for g++):
Under the description of -std, the man page lists all C++ standards, including the GNU dialects. Under one specific standard, it is rather inconspicuously stated, This is the default for C++ code. (there is an analogous statement for C standards: This is the default for C code.).
For instance, for g++/gcc version 5.4.0, this is listed under gnu++98/gnu++03, whereas for g++/gcc version 6.4.0, this is listed under gnu++14.
I'm guessing a default version of the C++ compiler gets called, but I don't know which?
This is only guessable by reading the documentation of your particular compiler version.
If using a recent GCC, I recommend first to understand what version are you using by running
g++ -v
or
g++ --version
and then refer to the version of the particular release of GCC. For example for GCC 7, read GCC 7 changes etc
Alternatively, run
g++ -dumpspecs
and decipher the default so called spec file.
BTW, you could ensure (e.g. in some of your common header file) that C++ is at least C++17 by coding
#if __cplusplus < 201412L
#error expecting C++17 standard
#endif
and I actually recommend doing it that way.
PS. Actually, think of C++98 & C++17 being two different languages (e.g. like Ocaml4 and C++11 are). Require your user to have a compiler supporting some defined language standard (e.g. C++11), not some particular version of GCC. Read also about package managers.
If you are using the GCC compiler, you can find it on the man pages:
man g++ | grep "This is the default for C++ code"
Typing g++ --version in your command shell will reveal the version of the compiler, and from that you can infer the default standard. So you can't tell directly but you can infer it, with some effort.
Compilers are supposed to #define __cplusplus which can be used to extract the standard that they purport to implement at compile time; but many don't do this yet.
(And don't forget to include all the C++ standard library headers you need: where is the one for std::string for example? Don't rely on your C++ standard library implementation including other headers automatically - in doing that you are not writing portable C++.)
Your question is specific to gnu compilers, so probably better to tag it appropriately, rather than just C++ and C++11.
Your code will compile with any compilers (and associated libraries) compliant with C++11 and later.
The reason is that C++11 introduced a std::ifstream constructor that accepts a const std::string &. Before C++11, a std::string could not be passed, and it would be necessary in your code to pass filename.c_str() rather than filename.
According to information from gnu, https://gcc.gnu.org/projects/cxx-status.html#cxx11, gcc.4.8.1 was the first version to fully support C++11. At the command line g++ -v will prod g++ to telling you its version number.
If you dig into documentation, you might be able to find the version/subversion that first supported enough features so your code - as given - would compile. But such a version would support some C++11 features and not others.
Since windows isn't distributed with g++, you will have whatever version someone (you?) has chosen to install. There will be no default version of g++ associated with your version of windows.
The default language standards for both C and C++ are specified in the GCC Manuals. You can find these as follows:
Browse to https://gcc.gnu.org/onlinedocs/
Select the GCC #.## Manual link for the version of GCC you are interested in, e.g. for GCC 7.5.0:
https://gcc.gnu.org/onlinedocs/gcc-7.5.0/gcc/
Click the topic link Language Standards Supported by GCC, followed by the topic C++ Language (or C language). Either of these topics will have a sentence such as:
The default, if no C++ language dialect options are given, is -std=gnu++14.
The default, if no C language dialect options are given, is -std=gnu11.
The above two examples are for GCC 7.5.0.

Which C++ standard is the default when compiling with g++?

I have a piece of code that looks like the following. Let's say it's in a file named example.cpp
#include <fstream>
#include <string> // line added after edit for clarity
int main() {
std::string filename = "input.txt";
std::ifstream in(filename);
return 0;
}
On a windows, if I type in the cmd the command g++ example.cpp, it will fail. It's a long list of errors I think mostly due to the linker complaining about not being able to convert from string to const char*.
But if I run the compiler using an additional argument like so: g++ -std=c++17 example.cpp, it will compile and work fine with no problems.
What happens when I run the former command? I'm guessing a default version standard of the C++ compiler gets called, but I don't know which? And as a programmer/developer, should I always use the latter command with the extra argument?
If your version of g++ is later than 4.7 I think you can find the default version of C++ standard supported like so:
g++ -dM -E -x c++ /dev/null | grep -F __cplusplus
An example from my machine:
mburr#mint17 ~ $ g++ --version | head -1
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
mburr#mint17 ~ $ g++ -dM -E -x c++ /dev/null | grep -F __cplusplus
#define __cplusplus 199711L
Some references:
Details on the g++ options used
Why this only works for g++ 4.7 or later
g++ man page actually tells what is the default standard for C++ code.
Use following script to show the relevant part:
man g++ | col -b | grep -B 2 -e '-std=.* This is the default'
For example, in RHEL 6 g++ (GCC) 4.4.7 20120313 (Red Hat 4.4.7-23), the output:
gnu++98
GNU dialect of -std=c++98. This is the default for C++ code.
And in Fedora 28 g++ (GCC) 8.1.1 20180502 (Red Hat 8.1.1-1), the output:
gnu++14
gnu++1y
GNU dialect of -std=c++14. This is the default for C++ code. The name gnu++1y is deprecated.
You can also check with gdb
$ g++ example.cpp -g Compile program with -g flag to generate debug info
$ gdb a.out Debug program with gdb
(gdb) b main Put a breakpoint at main
(gdb) run Run program (will pause at breakpoint)
(gdb) info source
Prints out something like:
Current source file is example.cpp
Compilation directory is /home/xxx/cpp
Located in /home/xxx/cpp/example.cpp
Contains 7 lines.
Source language is c++.
Producer is GNU C++14 6.3.0 20170516 -mtune=generic -march=x86-64 -g.
Compiled with DWARF 2 debugging format.
Does not include preprocessor macro info.
There is the standard used by compiler: Producer is GNU C++14
If you recompile your program using -std=c++11 (for example), gdb detects it:
Producer is GNU C++11
I believe that it is possible to tell by looking at the man page (at least for g++):
Under the description of -std, the man page lists all C++ standards, including the GNU dialects. Under one specific standard, it is rather inconspicuously stated, This is the default for C++ code. (there is an analogous statement for C standards: This is the default for C code.).
For instance, for g++/gcc version 5.4.0, this is listed under gnu++98/gnu++03, whereas for g++/gcc version 6.4.0, this is listed under gnu++14.
I'm guessing a default version of the C++ compiler gets called, but I don't know which?
This is only guessable by reading the documentation of your particular compiler version.
If using a recent GCC, I recommend first to understand what version are you using by running
g++ -v
or
g++ --version
and then refer to the version of the particular release of GCC. For example for GCC 7, read GCC 7 changes etc
Alternatively, run
g++ -dumpspecs
and decipher the default so called spec file.
BTW, you could ensure (e.g. in some of your common header file) that C++ is at least C++17 by coding
#if __cplusplus < 201412L
#error expecting C++17 standard
#endif
and I actually recommend doing it that way.
PS. Actually, think of C++98 & C++17 being two different languages (e.g. like Ocaml4 and C++11 are). Require your user to have a compiler supporting some defined language standard (e.g. C++11), not some particular version of GCC. Read also about package managers.
If you are using the GCC compiler, you can find it on the man pages:
man g++ | grep "This is the default for C++ code"
Typing g++ --version in your command shell will reveal the version of the compiler, and from that you can infer the default standard. So you can't tell directly but you can infer it, with some effort.
Compilers are supposed to #define __cplusplus which can be used to extract the standard that they purport to implement at compile time; but many don't do this yet.
(And don't forget to include all the C++ standard library headers you need: where is the one for std::string for example? Don't rely on your C++ standard library implementation including other headers automatically - in doing that you are not writing portable C++.)
Your question is specific to gnu compilers, so probably better to tag it appropriately, rather than just C++ and C++11.
Your code will compile with any compilers (and associated libraries) compliant with C++11 and later.
The reason is that C++11 introduced a std::ifstream constructor that accepts a const std::string &. Before C++11, a std::string could not be passed, and it would be necessary in your code to pass filename.c_str() rather than filename.
According to information from gnu, https://gcc.gnu.org/projects/cxx-status.html#cxx11, gcc.4.8.1 was the first version to fully support C++11. At the command line g++ -v will prod g++ to telling you its version number.
If you dig into documentation, you might be able to find the version/subversion that first supported enough features so your code - as given - would compile. But such a version would support some C++11 features and not others.
Since windows isn't distributed with g++, you will have whatever version someone (you?) has chosen to install. There will be no default version of g++ associated with your version of windows.
The default language standards for both C and C++ are specified in the GCC Manuals. You can find these as follows:
Browse to https://gcc.gnu.org/onlinedocs/
Select the GCC #.## Manual link for the version of GCC you are interested in, e.g. for GCC 7.5.0:
https://gcc.gnu.org/onlinedocs/gcc-7.5.0/gcc/
Click the topic link Language Standards Supported by GCC, followed by the topic C++ Language (or C language). Either of these topics will have a sentence such as:
The default, if no C++ language dialect options are given, is -std=gnu++14.
The default, if no C language dialect options are given, is -std=gnu11.
The above two examples are for GCC 7.5.0.

MinGW gcc gives errors when other compilers do not

Before you asked, yes i did look this up FOR DAYS. Im completely stuck... I'm using MINGW32 (my shortcut says MSYS) to compile my c and cpp code. For about 2 or 3 days now I have been getting strange errors. (below) It was working JUST FINE before. I even ran the same code i've compiled before and it gave the same error. I then go into DevC++ and open then compile an it works just fine.
ERRORS:
namespace: command not found
using: command not found
syntax error:
int main(){
(sometimes it gives me a big unreadable mess)
I'm really stuck... I dont want to have to switch to DevC++... I like to use my own text editor and compile in a command line.
From your errors namespace: command not found and using: command not found says to me that you aren't compiling the code with an appropriate compiler.
For reference in MinGW32 toolchain:
gcc.exe = C
g++.exe = C++
You may find it useful to take a look at what the IDE's actualy do with your compiler.
My current IDE allows me to see all the commands that it runs to build my project:
C:/mingw32/bin/g++.exe -c "C:/MyProgram/main.cpp" -g -O0 -std=c++14 -Wall -o ./Obj/main.cpp.o -I. -IDependencies/Something/include
So lets examine what this does.
My current toolchain is MinGW32 which is located in C:/mingw32/bin/g++.exe
g++ is our c++ compiler so we call g++.exe and we pass the following switch:
-c "C:/MyProgramm/main.cpp"
This tells my compiler to compile the main.cpp from my project directory. then my IDE adds a few additional command line switches. For the purpose of the answer I will only consider -o. This tells us the output file from our code main.cpp into an output file.
The reason we produce such a file is to save us time compiling so that we do not have to compile the same file twice without making changes to it. We perform this step on each of our files creating a collection of .o files.
The new file is then saved in "C:/MyProgramm/Obj/main.cpp.o"
Which means that your command line function will look something like this:
C:/mingw32/bin/g++.exe -c "<my project directory>/<file>.cpp" -o ./Obj/<file>.cpp.o
I would recommend that you read up on documentation for the g++ function and learn from different IDE's as you will soon find that you need to do more advanced things with your compiler.
For example to enable features from c++14 I add -std=c++14
*Edited to reflect feedback.

Does g++ work without gcc?

Does G++ compile without GCC or G++ is just translator // Including old g++ version.
when i was trying to install g++ from source i saw file
gcc.c
/* Default prefixes to attach to command names. */
#ifndef STANDARD_EXEC_PREFIX
#define STANDARD_EXEC_PREFIX "/usr/local/lib/gcc-"
#endif /* !defined STANDARD_EXEC_PREFIX */
//from g++1.4*
Well i know that c++ is c with classes i just wanted to know if the g++ can compile c++ without gcc .
With a recent GCC, gcc (actually cc1 which is run by gcc) and g++ (actually cc1plus) -and so on for other GCC compilers, e.g. gfortran or even gdc ....- share a lot of (source) code together: the middle-end (where most optimizations happen) and the back-end. The difference is only the front-end layer of the compiler (the only layer being source language specific) which is less than 30% of the compiler.
You could customize the GCC compiler with plugins or with MELT. Your extensions would work on GCC internal representations (Gimple-s) and would work when compiling C, C++, Ada, Fortran, etc... Remember that GCC means Gnu Compiler Collection today
Actually the gcc program is able to compile C++ source code (and likewise g++ can compile C or Fortran code). However, they are not linking the same libraries.
Pass the -v flag to the gcc or g++ command to understand what they are running.
Here are two (mine) [CC-BY-SA] pictures -explaing GCC & MELT- illustrating this.
The three layers -front-end, middle-end, back-end- of the compiler:
with your plugin, or the MELT meta-plugin
with a simplification: cc1 or cc1plus are generating assembler files, which is then translated by as started by gcc or g++
and
another view of the internals of cc1 or cc1plus,
which generates some assembler code

How configure include path and use standard library with gcc compiler?

I know this topic was few times there, but I can't get satisfactory answer.
C:\Users\Krzysiek>gcc test.c
test.c:3:20: fatal error: iostream: No such file or directory
compilation terminated.
This is what I try to do
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}
Simple program with "include"
I've heard of LIBRARY_PATH. So I've setted that. Still this same error I have.
GCC provides wrappers around calling its various compilers.
You are using gcc, which is for C (and consequently will not include or link the C++ standard library; the compiler would go on to complain about the rest of your code, too, since it's not valid C);
Use g++, which is for C++.
Also try to use a conventional extension for C++ source files, which is .cc, .cxx or .cpp.
Use g++ instead: it will link to the c++ standard library.
When you use the gcc command, gcc looks at the file extension to decide which language to use to compile. As you used a .c file, gcc will switch by default to C.
# Use the C compiler
gcc test.c
# Use the C++ compiler
gcc test.cpp
To choose a different language, you can use the -x option:
# Use the C++ compiler even if the extension is .c
gcc -xc++ test.c
Another method of using the C++ compiler is to use g++ in the command line. This is the preferred way, as it links with the correct libraries.
# Use the C++ compiler
g++ test.c