Reputation: 3742
My program needs to communicate with a serial device. I am developing it on Ubuntu 14.04 LTS. I found libserial, and tried to use it, but it does not compile. I downloaded, compiled and installed v0.6.0rc2. Yeah, it is a rc, but it is more popular on sourceforge and the stable releases are very old. If you know a better library, please tell it to me in the comments.
The code given below as per the docs doesnot compile:
#include <SerialStream.h>
//
using namespace LibSerial ;
main()
{
SerialStream my_serial_stream ;
//
// Open the serial port for communication.
//
my_serial_stream.Open( "/dev/ttyS0" ) ;
}
This is the error I get:
dalton@dalton-SVF14212SNW:~$ g++ test.cpp
/tmp/ccyWIbXN.o: In function `main':
test.cpp:(.text+0x17): undefined reference to `LibSerial::SerialStream::SerialStream()'
test.cpp:(.text+0x6d): undefined reference to `LibSerial::SerialStream::Open(std::string, std::_Ios_Openmode)'
test.cpp:(.text+0x9a): undefined reference to `LibSerial::SerialStream::~SerialStream()'
test.cpp:(.text+0xd6): undefined reference to `LibSerial::SerialStream::~SerialStream()'
collect2: error: ld returned 1 exit status
I've changed the line in question to my_serial_stream.Open( "/dev/ttyS0" , ios::out ) ;
and added namespace std
. Now I get this error:
dalton@dalton-SVF14212SNW:~$ g++ test.cpp
/tmp/ccUhSQVA.o: In function `main':
test.cpp:(.text+0x17): undefined reference to `LibSerial::SerialStream::SerialStream()'
test.cpp:(.text+0x5f): undefined reference to `LibSerial::SerialStream::Open(std::string, std::_Ios_Openmode)'
test.cpp:(.text+0x8c): undefined reference to `LibSerial::SerialStream::~SerialStream()'
test.cpp:(.text+0xc8): undefined reference to `LibSerial::SerialStream::~SerialStream()'
collect2: error: ld returned 1 exit status
Upvotes: 0
Views: 3534
Reputation: 1362
You need to link the library to your code.
try using
g++ test.cpp -L<PATH_TO_LIB_SERIAL_LIBRARY_DIR> -lserial
Lets assume you installed libserial in /usr/local/lib (libserial.a or libserial.so is in /usr/local/lib) you'd use the following command to compile and link your program
g++ test.cpp -L/usr/local/lib -lserial
The error output you posted, shows that the error occurred during the linking phase.
See What is an undefined reference/unresolved external symbol error and how do I fix it?
for more information on what may cause the the linking errors.
In this case it looks like you didn't link to the library.
Upvotes: 1