How to compile C++ under Ubuntu Linux? - c++

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.

Related

Build library libtorrent debian and link it to program c++

I always have problems when building libraries and linking them, so I hope someone can give me a hand.
I downloaded libtorrent from here and I've built it like they explain here in the building with autotools section (skipping step 1). The building process was successfull I think, but when I did make check the output was:
============================================================================
Testsuite summary for libtorrent-rasterbar 1.0.5
============================================================================
# TOTAL: 0
# PASS: 0
# SKIP: 0
# XFAIL: 0
# FAIL: 0
# XPASS: 0
# ERROR: 0
============================================================================
Maybe it should say: total X?
I did a little program where I added #include <libtorrent/session.hpp> and when I compile with g++ file.cpp -o file it says libtorrent/session.hpp: No such file or directory.
Should I add some flags to g++ such as -lpthread for other projects and thinks like that?
Thanks
UPDATE:
When installing without building using sudo apt-get install libtorrent-rasterbar-dev and compiling my main.cpp file I get this error:
g++ main.cpp -o file
In file included from /usr/include/libtorrent/session.hpp:49:0,
from main.cpp:2:
/usr/include/libtorrent/config.hpp:46:2: error: #error you must define either BOOST_ASIO_SEPARATE_COMPILATION or BOOST_ASIO_DYN_LINK in your project in order for asio's declarations to be correct. If you're linking dynamically against libtorrent, define BOOST_ASIO_DYN_LINK otherwise BOOST_ASIO_SEPARATE_COMPILATION. You can also use pkg-config or boost build, to automatically apply these defines
#error you must define either BOOST_ASIO_SEPARATE_COMPILATION or BOOST_ASIO_DYN_LINK in your project in \
UPDATE 2:
Modified the main.cpp file to add the the following above the libtorrent #include directives:
#ifndef BOOST_ASIO_DYN_LINK
#define BOOST_ASIO_DYN_LINK
#endif
But then I have this problem:
$ g++ main.cpp
/tmp/ccM2ItFb.o: In function `main':
main.cpp:(.text+0x57): undefined reference to `libtorrent::default_storage_constructor(libtorrent::file_storage const&, libtorrent::file_storage const*, std::string const&, libtorrent::file_pool&, std::vector<unsigned char, std::allocator<unsigned char> > const&)'
main.cpp:(.text+0xb9): undefined reference to `libtorrent::session::~session()'
main.cpp:(.text+0x105): undefined reference to `libtorrent::session::~session()'
/tmp/ccM2ItFb.o: In function `__static_initialization_and_destruction_0(int, int)':
main.cpp:(.text+0x162): undefined reference to `boost::system::generic_category()'
main.cpp:(.text+0x16e): undefined reference to `boost::system::generic_category()'
main.cpp:(.text+0x17a): undefined reference to `boost::system::system_category()'
main.cpp:(.text+0x192): undefined reference to `boost::asio::error::get_netdb_category()'
main.cpp:(.text+0x19e): undefined reference to `boost::asio::error::get_addrinfo_category()'
main.cpp:(.text+0x1aa): undefined reference to `boost::asio::error::get_misc_category()'
/tmp/ccM2ItFb.o: In function `boost::asio::error::get_system_category()':
main.cpp (.text._ZN5boost4asio5error19get_system_categoryEv[_ZN5boost4asio5error19get_system_categoryEv]+0x5): undefined reference to `boost::system::system_category()'
/tmp/ccM2ItFb.o: In function `libtorrent::session::session(libtorrent::fingerprint const&, int, unsigned int)':
main.cpp:(.text._ZN10libtorrent7sessionC2ERKNS_11fingerprintEij[_ZN10libtorrent7sessionC5ERKNS_11fingerprintEij]+0x3c): undefined reference to `libtorrent::rel_clocktime_pools_nolog_resolvecountries_deprecated_dht_ext_()'
main.cpp:(.text._ZN10libtorrent7sessionC2ERKNS_11fingerprintEij[_ZN10libtorrent7sessionC5ERKNS_11fingerprintEij]+0x75): undefined reference to `libtorrent::session::init(std::pair<int, int>, char const*, libtorrent::fingerprint const&, int, unsigned int)'
/tmp/ccM2ItFb.o: In function `void boost::checked_delete<libtorrent::torrent_info const>(libtorrent::torrent_info const*)':
main.cpp:(.text._ZN5boost14checked_deleteIKN10libtorrent12torrent_infoEEEvPT_[_ZN5boost14checked_deleteIKN10libtorrent12torrent_infoEEEvPT_]+0x1a): undefined reference to `libtorrent::torrent_info::~torrent_info()'
collect2: error: ld returned 1 exit status
Also tried compiling using: g++ -I /usr/include/ -L /usr/local/lib -lboost_system -lpthread -lboost_thread main.cpp with the same result.
UPDATE 3:
I was able to solve the problem. I had to compile using:
g++ -I /usr/include/ -L /usr/local/lib -lboost_system -lpthread -lboost_thread main.cpp and add also the link library -ltorrent-rasterbar
Sounds like you've compiled the library but not actually installed it anywhere. An #include directive looks in /usr/include by default, but the libtorrent headers are somewhere in the directory where you built the library. You'll need to either install the library's files into the system directories, or give the compiler an -I option pointing to the libtorrent build directory. (You'll probably also need an -L option when linking, for the same reason.)

OCCI compilation with g++ in Linux

I'm trying to compile a basic program using OCCI library.
The compilation task is OK.
g++ -I. -g -I/opt/oracle/product/10.2.0/db_1/precomp/public -I/opt/oracle/product/10.2.0/db_1/rdbms/public -I/opt/oracle/product/10.2.0/db_1/rdbms/demo -I/opt/oracle/product/10.2.0/db_1/plsql/public -I/opt/oracle/product/10.2.0/db_1/network/public -DMAX_SEND_SIZE=2000 -c -o test.o test.cpp
the output is OK, test.o is generated. But, when I want to link the object file, with the following command,
g++ -L/opt/oracle/product/10.2.0/db_1/lib/ -lclntsh -locci -o test test.o
The linking task fails, the output is:
test.o: In function `main':
/home/xxx/occi/test.cpp:128: undefined reference to `oracle::occi::Environment::createEnvironment(oracle::occi::Environment::Mode, void*, void* (*)(void*, unsigned int), void* (*)(void*, void*, unsigned int), void (*)(void*, void*))'
/home/xxx/occi/test.cpp:170: undefined reference to `oracle::occi::Environment::terminateEnvironment(oracle::occi::Environment*)'
/home/xxx/occi/test.cpp:158: undefined reference to `oracle::occi::SQLException::~SQLException()'
/home/xxx/occi/test.cpp:158: undefined reference to `oracle::occi::SQLException::SQLException(oracle::occi::SQLException const&)'
/home/xxx/occi/test.cpp:163: undefined reference to `oracle::occi::SQLException::what() const'
/home/xxx/occi/test.cpp:158: undefined reference to `oracle::occi::SQLException::~SQLException()'
test.o:(.gcc_except_table+0xe0): undefined reference to `typeinfo for oracle::occi::SQLException'
collect2: ld returned 1 exit status
My environment resume:
Ubuntu Linux 11.04
gcc version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3)
ORACLE_HOME = /opt/oracle/product/10.2.0/db_1
LD_LIBRARY_PATH = /opt/oracle/product/10.2.0/db_1/lib
Oracle version: 10.2.0
Can you help me please?, I really need to create a connection to Oracle using OCCI in Linux and I don't want to use Pro*C.
To use OCCI you need to install Instant Client provided by Oracle (have you installed?). I'm using Oracle 11.2, so my include directory path is /usr/include/oracle/11.2/client64 and my share libraries is /usr/lib/oracle/11.2/client64/lib.
I saw here
http://173.255.217.246:8000/mapnik_trac/wiki/OCCI
that 10.2 path is /usr/lib/oracle/10.2.0.4/client/include and /usr/lib/oracle/10.2.0.4/client/lib
In 11.2, I also need to link with nnz11 lib first as http://xme.im/connect-oracle-database-eclipse-linux-using-occi
This is an usefull blog describe about Instant Client http://oradim.blogspot.com/2009/08/getting-started-with-occi-linux-version.html

Linking against boost_thread fails under Ubuntu 11.10

I already updated to the new Ubuntu 11.10.The problem is now, that the software I am working on is not linking any more. I found this wiki entry which seems to describe the problem. None the less I am unable to fix it. To reproduce the problem I wrote the following small test program:
#include <iostream>
#include <boost/thread.hpp>
void blubb() {
std::cout << "hello world" << std::endl;
}
int main() {
boost::thread t(&blubb);
t.join();
}
Than I use the following command to compile:
g++ -o test -lboost_thread test.cc
The output I get is the following:
/tmp/cc0O0dAC.o: In function `main':
test.cc:(.text+0x49): undefined reference to `boost::thread::join()'
test.cc:(.text+0x55): undefined reference to `boost::thread::~thread()'
test.cc:(.text+0x70): undefined reference to `boost::thread::~thread()'
/tmp/cc0O0dAC.o: In function `boost::detail::thread_data_base::thread_data_base()':
test.cc:(.text._ZN5boost6detail16thread_data_baseC2Ev[_ZN5boost6detail16thread_data_baseC5Ev]+0x24): undefined reference to `vtable for boost::detail::thread_data_base'
/tmp/cc0O0dAC.o: In function `boost::thread::thread<void (*)()>(void (*)(), boost::disable_if<boost::is_convertible<void (*&)(), boost::detail::thread_move_t<void (* ()> >, boost::thread::dummy*>::type)':
test.cc:(.text._ZN5boost6threadC2IPFvvEEET_NS_10disable_ifINS_14is_convertibleIRS4_NS_6detail13thread_move_tIS4_EEEEPNS0_5dummyEE4typeE[_ZN5boost6threadC5IPFvvEEET_NS_10disable_ifINS_14is_convertibleIRS4_NS_6detail13thread_move_tIS4_EEEEPNS0_5dummyEE4typeE]+0x30): undefined reference to `boost::thread::start_thread()'
/tmp/cc0O0dAC.o: In function `boost::detail::thread_data<void (*)()>::~thread_data()':
test.cc:(.text._ZN5boost6detail11thread_dataIPFvvEED2Ev[_ZN5boost6detail11thread_dataIPFvvEED5Ev]+0x1f): undefined reference to `boost::detail::thread_data_base::~thread_data_base()'
/tmp/cc0O0dAC.o:(.rodata._ZTIN5boost6detail11thread_dataIPFvvEEE[typeinfo for boost::detail::thread_data<void (*)()>]+0x10): undefined reference to `typeinfo for boost::detail::thread_data_base'
collect2: ld returned 1 exit status
I also tried to add -lpthread and -pthread in several orders with no success. This command works smoothly on an older Ubuntu version. What am I doing wrong (I have similar problems with PCRE and Google Protocol Buffers).
Thanks in advance for any help!
Ok I mamaged to fix it, it is ridiculous:
as written in the question
g++ -o test -lboost_thread test.cc
does not work, but
g++ -o test test.cc -lboost_thread
does... So not only the order of libraries matter, but also the source files must be written before the dependencies...

How to compile a c++ program in Linux?

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

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.