How to compile a c++ program in Linux? - c++

I made a file hi.cpp and I wrote the command given below:
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World! ";
cout << "I'm a C++ program";
return 0;
}
then I ran it in my RHEL 6 machine with the following command
gcc hi.cpp
and I got some errors which are as follows:
[chankey#localhost ~]$ gcc hi.cpp
/tmp/cc32bnmR.o: In function `main':
hi.cpp:(.text+0xa): undefined reference to `std::cout'
hi.cpp:(.text+0xf): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, const char*)'
hi.cpp:(.text+0x19): undefined reference to `std::cout'
hi.cpp:(.text+0x1e): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, const char*)'
/tmp/cc32bnmR.o: In function `__static_initialization_and_destruction_0(int, int)':
hi.cpp:(.text+0x4c): undefined reference to `std::ios_base::Init::Init()'
hi.cpp:(.text+0x51): undefined reference to `std::ios_base::Init::~Init()'
/tmp/cc32bnmR.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
[chankey#localhost ~]$
What do these errors denote? My code is correct then why am I getting errors?

Use g++
g++ -o hi hi.cpp
g++ is for C++, gcc is for C although with the -libstdc++ you can compile c++ most people don't do this.

As the other answers say, use g++ instead of gcc.
Or use make: make hi

You have to use g++ (as mentioned in other answers). On top of that you can think of providing some good options available at command line (which helps you avoid making ill formed code):
g++ -O4 -Wall hi.cpp -o hi.out
^^^^^ ^^^^^^
optimize related to coding mistakes
For more detail you can refer to man g++ | less.

Try this:
g++ -o hi hi.cpp
gcc is only for C

For a simple hello-world project, calling the compiler directly with g++ command or creating a make file are good options as already answered:
g++ -o hi hi.cpp
or
# After creating the makefile
make hi
For serious projects, however, the usage of a project manager is required. At the time I write this answer, the most used and open-source is cmake (an alternative could be QT qmake ).
Following is a simple CMake example:
Make sure you installed cmake on your linux distribution apt-get install cmake or yum install cmake.
Create a file CMakeLists.txt (the name is important) together with your source hi.cpp
project("hi")
add_executable( hi hi.cpp )
Then compile and run as:
cmake -B <path_to_build_folder> -S <path_to_source_folder>
cmake --build <path_to_build_folder>
cd <path_to_build_folder>; ./hi
This allows the project to scale easily with libraries, sources, unit-tests, and much more. It also makes most IDEs to understand the project properly (Most IDEs accept CMake natively, like kdevelop, qtCreator, etc..)
You could also generate Visual-Studio or XCode projects from CMake, in case you decide to port the software to other platforms in the future.
cmake -G Xcode . #will generate `hi.xcodeproj` you can load on macOS

$ g++ 1st.cpp -o 1st
$ ./1st
if you found any error then first install g++ using code as below
$ sudo apt-get install g++
then install g++ and use above run code

g++ -o foo foo.cpp
g++ --> Driver for cc1plus compiler
-o --> Indicates the output file (foo is the name of output file here. Can be any name)
foo.cpp --> Source file to be compiled
To execute the compiled file simply type
./foo

To Compile your C++ code use:-
g++ file_name.cpp -o executable_file_name
(i) -o option is used to show error in the code
(ii) if there is no error in the code_file, then it will generate
an executable file.
Now execute the generated executable file:
./executable_file_name

Related

error when runing .cpp file in terminal using g++

I trying RabbitMQ + C++. Working on linux ubuntu 16.04. Have working code and when I compile using CLion all works fine.
I have peace of code what I need to run with root, so I want to run it using g++.
ERROR FROM TERMINAL
In function `main':
receiveUNPW.cpp:(.text+0x8e8): undefined reference to `SimplePocoHandler::SimplePocoHandler(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned short)'
receiveUNPW.cpp:(.text+0xc9c): undefined reference to `SimplePocoHandler::loop()'
receiveUNPW.cpp:(.text+0xcce): undefined reference to `SimplePocoHandler::~SimplePocoHandler()'
receiveUNPW.cpp:(.text+0xea7): undefined reference to `SimplePocoHandler::~SimplePocoHandler()'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../../lib/libamqpcpp.so: undefined reference to `pthread_create'
I write :
g++ -std=c++11 receiveUNPW.cpp -o receiveUNPW -lcrypt -lPocoNet -lPocoFoundation -lamqpcpp
CMakeList.txt
cmake_minimum_required(VERSION 3.5)
project(test)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_library(poco_simple_handler SimplePocoHandler.cpp SimplePocoHandler.h)
target_link_libraries(poco_simple_handler PocoNet PocoFoundation crypt )
set(PROGS
sendUNPW
receiveUNPW
)
foreach(item ${PROGS})
add_executable(${item} "${item}.cpp")
target_link_libraries(${item} amqpcpp poco_simple_handler PocoNet PocoFoundation crypt)
endforeach(item)
MY IDEA
As can see when I use g++ it can't find reference to SimplePocoHandler. In CmakeList.txt i have
add_library(poco_simple_handler SimplePocoHandler.cpp SimplePocoHandler.h)
target_link_libraries(poco_simple_handler PocoNet PocoFoundation crypt )
so when I compile in CLion all works fine. So seems I need to do the same when I using g++. But I don't know how to do it, any suggestions or explanations would be great.
I don't share my receiveUNPW.cpp code, but it's almost similar to that receiver.cpp what you can see there and also I don't have any error there, in CLion all works fine, I just need to run my program using terminal with root permissions.
To run your code as root, change to a root shell using su - and then execute the binary that CLion generated. Or run it using sudo. You can also set the suid bit on the executable and make it be owned by root then it will always run as root, but that's not recommended - too many security issues possible.
You don't need to recompile an application as root to run it as root.
Edit with example as requested:
A simple program:
#include <iostream>
int main() {
std::cout << "Hello world\n";
}
Compiling it:
$ g++ hello.cc
Running it:
$ ./a.out
Hello world
$
Running it as root:
$ su -
# /path/to/program/a.out
Hello world
#

Linker Error using g++ with Qt 4.5.1

I'm trying to test out a new dev environment and I am having some problems referencing some of the required Qt libraries.
First I ran this:
$ g++ HelloWorld.C -o HelloWorld -I /usr/local/Trolltech/Qt-4.5.1/include/QtCore/ -I /usr/local/Trolltech/Qt-4.5.1/include/
and got this error:
/tmp/ccmsm4kZ.o: In function `QString::QString(char const*)':
HelloWorld.C:(.text._ZN7QStringC2EPKc[_ZN7QStringC5EPKc]+0x1d): undefined reference to `QString::fromAscii_helper(char const*, int)'
/tmp/ccmsm4kZ.o: In function `QString::~QString()':
HelloWorld.C:(.text._ZN7QStringD2Ev[_ZN7QStringD5Ev]+0x2d): undefined reference to `QString::free(QString::Data*)'
collect2: ld returned 1 exit status
So then I added reference to the QtCore library via:
$ g++ HelloWorld.C -o HelloWorld -I /usr/local/Trolltech/Qt-4.5.1/include/QtCore/ -I /usr/local/Trolltech/Qt-4.5.1/include/ -L /usr/local/Trolltech/Qt-4.5.1/lib -lQtCore
which removed the compile errors, however when I try to run the program I get this error:
./HelloWorld: error while loading shared libraries: libQtCore.so.4: cannot open shared object file: No such file or directory
I wasn't able to find a solution for this problem via google. Anyone have advice?
That error indicates that while the linker can find the library at compilation, it can't find it during runtime.
You should update your LD_LIBRARY_PATH to include that location like this:
In ~.bashrc probably somewhere near the bottom:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/Trolltech/Qt-4.5.1/lib
Alternatively, if you want to make this persistent throughout your system (and have root access), you can make an entry in /etc/ld.so.conf.d (on RedHat, I'm not sure about the other distributions)
touch /etc/ld.so.conf.d/qt.conf
Add the path to this file, and then update your runtime via /sbin/ldconfig

Google RE2 library cannot compile with 'make testinstall' in ubuntu

Gurus!
I am using Ubuntu 13.10 64-bit to compile latest Google RE2 library, but 'make testinstall' failed to compile, here is the log:
kevin#ubuntu:~/re2$ make testinstall
cp testinstall.cc obj
(cd obj && g++ -I/usr/local/include -L/usr/local/lib testinstall.cc -lre2 -pthread -o testinstall)
/tmp/ccSsaSXS.o: In function main':
testinstall.cc:(.text+0xce): undefined reference tore2::FilteredRE2::FirstMatch(re2::StringPiece const&, std::vector > const&) const'
/usr/local/lib/libre2.so: undefined reference to pthread_rwlock_rdlock'
/usr/local/lib/libre2.so: undefined reference topthread_rwlock_wrlock'
/usr/local/lib/libre2.so: undefined reference to pthread_rwlock_destroy'
/usr/local/lib/libre2.so: undefined reference topthread_rwlock_init'
/usr/local/lib/libre2.so: undefined reference to `pthread_rwlock_unlock'
collect2: error: ld returned 1 exit status
make: * [testinstall] Error 1
I tried to replace -pthread with -lpthread, still failed, then I dumped libre2.so and found that pthread_xxx is in it.
Here is the issue tracking in RE2 forum: https://code.google.com/p/re2/issues/detail?id=100
Anyone here have ever complied RE2 successfully ? Thank you!
See this comment:
Adding -pthread to LDFLAGS seems to fix make test (all tests are
passing), but not make testinstall.
That will get you to the next error
Depending on what you build it for 'make testinstall' might not be necessary.
I just needed to get python re2 port working, and this can be installed after running make install.
I encounter this problem before. Modify the makefile and use -lpthread instead of -pthread.
So I tried looking for the lines in testinstall.cc that were causing the symbol errors and I found out that the only line was on line 18:
18 - f.firstMatch(:abbccc:, ids);
I commented this line out (so that the FullMatch function below is still called) and just ran g++ testinstall.cc -lre2 -pthread -o testinstall (basically what the Makefile does) and I was able to get a binary successfully. Although this might not really solve the problem, its good to know that we can still use the RE2::Fullmatch and partial match functions
If I were to guess, maybe there is a dependency somewhere inside the filtered_re2 module?
I had the same problem. But if you compile with -static everything goes well.
nm -C shows that the "missing" symbol exists in both .a and .so files.

undefined referance to LibSerial

So i'm writing a serial transmision program, and have just changed over to using C++, it been a while since I used C++
(I've been working with C recently, and before that java)
Now I need to use LibSerial,
(it seems much simpler to use than C's termios)
my code is:
//gen1.cpp
#include "string2num.h" // a custom header
#include <iostream>
#include <SerialStream.h>
using namespace LibSerial;
//using namespace std;
int main(int argc, char*argv[])
{
if (argc<2)
{
std::cout<<argv[0]<<"requires the device name eg \"dev/tty0\" as a parameter\nterminating.\n";
return 1;
}
SerialStream theSerialStream(argv[1]); //open the device
return 0;
}
When I compile the output:
g++ -Wall -o gen1 gen1.cpp string2num.o
/tmp/cchPBWgx.o: In function `main':
gen1.cpp:(.text+0x121): undefined reference to `LibSerial::SerialStream::SerialStream(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::_Ios_Openmode)'
/tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x24): undefined reference to `LibSerial::SerialStreamBuf::showmanyc()'
/tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x28): undefined reference to `LibSerial::SerialStreamBuf::xsgetn(char*, int)'
/tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x2c): undefined reference to `LibSerial::SerialStreamBuf::underflow()'
/tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x34): undefined reference to `LibSerial::SerialStreamBuf::pbackfail(int)'
/tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x38): undefined reference to `LibSerial::SerialStreamBuf::xsputn(char const*, int)'
/tmp/cchPBWgx.o:(.rodata._ZTVN9LibSerial15SerialStreamBufE[vtable for LibSerial::SerialStreamBuf]+0x3c): undefined reference to `LibSerial::SerialStreamBuf::overflow(int)'
collect2: ld returned 1 exit status
make: *** [gen1] Error 1
This is the linker complaining that it cannot find the functions referenced by the libserial header file.
If I look on my Linux system to see how the shared library is called:
$ dpkg -L libserial0
...
/usr/lib/libserial.so.0.0.0
/usr/lib/libserial.so.0
On my system this implies I would add -lserial as a g++ option (aka link with libserial.so) this would turn your compilation command into
g++ -Wall -lserial -o gen1 gen1.cpp string2num.o
Including the header file is not enough - you also need to link with the library that implements SerialStream. Assuming it is a static library called serstream.a (it is almost certainly actually called something else):
g++ -Wall -o gen1 gen1.cpp string2num.o serstream.a
old thread, but i still use Libserial. here the completed answer
My working setup.
Ubuntu 18.04
g++ 7.3.0
1) Install package for libserial
apt install libserial-dev
2) check for your headers(.h) and .so files
dpkg -l libserial0
dpkg -l libserial-dev
the first command give you the directory of shared library and the second gives you the headers location.
3) Your code.
I have to change a little your code, first i delete the custom header and modifing the constuctor call to this.
SerialStream theSerialStream;
4) compile with g++
Here my compiling command
g++ -o test -I/usr/include test.cpp -L/usr/lib/x86_64-linux-gnu -lserial -lpthread
check for the -lpthread linking option, beacuse Libserial uses mutex.
In Ubuntu/Debian make sure you have to libserial-dev package installed and use the '-lserial' flag for gcc.

How to compile C++ under Ubuntu Linux?

I cut&pasted the below code from a previous question into a file called "avishay.cpp" and then ran
gcc avishay.cpp
only to get the following error messages from the linker. What went wrong, what should I have done?
carl#carl-ubuntu:~/Projects/StackOverflow$ gcc -static avishay.cpp
/tmp/cccRNW34.o: In function `__static_initialization_and_destruction_0(int, int)':
avishay.cpp:(.text+0x41): undefined reference to `std::ios_base::Init::Init()'
avishay.cpp:(.text+0x46): undefined reference to `std::ios_base::Init::~Init()'
/tmp/cccRNW34.o: In function `A::func()':
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x11): undefined reference to `std::cout'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x16): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x1e): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x26): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x36): undefined reference to `std::cout'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x3b): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(int)'
/tmp/cccRNW34.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
The C++ code (not my code, I was just trying to run it):
#include <iostream>
using namespace std;
class A
{
private:
int _dmember;
public:
void func()
{
cout<<"Inside A!! "<<endl;
cout<<_dmember; // crash when reach here.
}
};
int main ()
{
A* a= NULL;
a->func(); // prints "Inside A!!!"
return 1;
}
You should use g++, not gcc, to compile C++ programs.
For this particular program, I just typed
make avishay
and let make figure out the rest. Gives your executable a decent name, too, instead of a.out.
You probably should use g++ rather than gcc.
Yes, use g++ to compile. It will automatically add all the references to libstdc++ which are necessary to link the program.
g++ source.cpp -o source
If you omit the -o parameter, the resultant executable will be named a.out. In any case, executable permissions have already been set, so no need to chmod anything.
Also, the code will give you undefined behaviour (and probably a SIGSEGV) as you are dereferencing a NULL pointer and trying to call a member function on an object that doesn't exist, so it most certainly will not print anything. It will probably crash or do some funky dance.
Update your apt-get:
$ sudo apt-get update
$ sudo apt-get install g++
Run your program.cpp:
$ g++ program.cpp
$ ./a.out
g++ is the C++ compiler under linux. The code looks right. It is possible that you are missing a library reference which is used as such:
g++ -l{library name here (math fns use "m")} codefile.cpp
Use
g++
space followed by the program name.
e.g:
g++ prog.cpp
if the filename was "prog.cpp" in this case.
if you want to run the program write:
./prog
so i used
"prog"
because it was my filename.
even you can compile your c++ code by gcc
Sounds funny ?? Yes it is.
try it
$ gcc avishay.cpp -lstdc++
enjoy
Use g++. And make sure you have the relevant libraries installed.
you can use g++ --std=c++0x example.cpp -o example
To compile source.cpp, run
g++ source.cpp
This command will compile source.cpp to file a.out in the same directory.
To run the compiled file, run
./a.out
If you compile another source file, with g++ source2.cpp, the new compiled file a.out will overwrite the a.out generated with source.cpp
If you want to compile source.cpp to a specific file, say compiledfile,
run
g++ source.cpp -o compiledfile
or
g++ -o compiledfile source.cpp
This will create the compiledfile which is the compiled binary file. to run the compiledfile, run
./compiledfile
If g++ is not in your $PATH, replace g++ with /usr/bin/g++.
Install gcc and try the video below.
Try this:
https://www.youtube.com/watch?v=A6v2Ceqy4Tk
Hope it will works for you.