I have a problem with compiling a boost integrated source code in my PC. I am working on below environment
OS: CentOs 6.3
Boost version: 1.41
Boost installation header file directory: /usr/include/boost/
IDE: code::block
Program for the compilation:
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
void ThreadFunction()
{
int counter = 0;
for(;;)
{
std::cout << "thread iteration " << ++counter << " Press Enter to stop" << std::endl;
try
{
// Sleep and check for interrupt.
// To check for interrupt without sleep,
// use boost::this_thread::interruption_point()
// which also throws boost::thread_interrupted
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
catch(boost::thread_interrupted&)
{
std::cout << "Thread is stopped" << std::endl;
return;
}
}
}
int main()
{
// Start thread
boost::thread t(&ThreadFunction);
// Wait for Enter
char ch;
std::cin.get(ch);
// Ask thread to stop
t.interrupt();
// Join - wait when thread actually exits
t.join();
std::cout << "main: thread ended" << std::endl;
return 0;
}
Error output:
Build: Debug in testPro (compiler: GNU GCC Compiler) ===|
obj/Debug/main.o||In function `main':|
<path to code>/main.cpp|40|undefined reference to `boost::thread::interrupt()'|
<path to code>/main.cpp|43|undefined reference to `boost::thread::join()'|
<path to code>/main.cpp|47|undefined reference to `boost::thread::~thread()'|
<path to code>/main.cpp|47|undefined reference to `boost::thread::~thread()'|
obj/Debug/main.o||In function `thread_data_base':|
/usr/include/boost/thread/pthread/thread_data.hpp|65|undefined reference to `vtable for boost::detail::thread_data_base'|
obj/Debug/main.o||In function `void boost::this_thread::sleep<boost::date_time::subsecond_duration<boost::posix_time::time_duration, 1000l> >(boost::date_time::subsecond_duration<boost::posix_time::time_duration, 1000l> const&)':|
/usr/include/boost/thread/pthread/thread_data.hpp|122|undefined reference to `boost::this_thread::sleep(boost::posix_time::ptime const&)'|
obj/Debug/main.o||In function `thread<void (*)()>':|
/usr/include/boost/thread/detail/thread.hpp|191|undefined reference to `boost::thread::start_thread()'|
obj/Debug/main.o||In function `~thread_data':|
/usr/include/boost/thread/detail/thread.hpp|40|undefined reference to `boost::detail::thread_data_base::~thread_data_base()'|
]+0x10)||undefined reference to `typeinfo for boost::detail::thread_data_base'|
||=== Build failed: 9 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|
As in the error console compiler cannot find the methods declared in boost library. I tried the several sample applications but result was the same. Please help me to find out the problem or suggest me a way to check the status of boost installation.
You need to compile your code with boost_thread library -lboost_thread
for example
gcc test.c -o test -lboost_thread
Related
I'm trying to do my first bit of threading but no matter what I've tried I can't get this to compile.
I've gone back to trying to compile some demo code and I'm getting the same problem as in my program.
If I run a simple print hello world it compiles and deploys the program fine and I can simply navigate to and run it directly on the Pi4.
Threading demo code
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
void* doSomeThing(void* arg)
{
unsigned long i = 0;
pthread_t id = pthread_self();
if (pthread_equal(id, tid[0]))
{
printf("\n First thread processing\n");
}
else
{
printf("\n Second thread processing\n");
}
for (i = 0; i < (0xFFFFFFFF); i++);
return NULL;
}
int main(void)
{
int i = 0;
int err;
while (i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread created successfully\n");
i++;
}
sleep(5);
return 0;
}
When I compile I get
Error /home/pi/projects/cpp_raspbian_thread_101/obj/x64/Debug/main.o: in function `main':
Error undefined reference to `pthread_create'
Error ld returned 1 exit status
To resolve this I've tried to add -pthread or -lpthread to
Project > Properties > Configuration Properties > C/C++ > Command Line > Addiitional Options
That does nothing, I'm not really sure if this is the correct place to put this.
I'm building in VS2019 so I'm not building from the command line, I don't know where to add this argument.
I have also tried installing pthreads in NuGet but that doesn't help.
Other software like VSCode seem to have files that could add this to but I'm lost in VS2019
Any help is appreciated.
EDIT:
Thanks for responses
OK so as #Eljay suggested I'm trying to use std::thread (again) but have the same problem.
// thread example
#include <iostream>
#include <thread>
void foo()
{
// do stuff...
}
int main()
{
std::thread first(foo);
return 0;
}
Log file
Validating sources
Copying sources remotely to '10.0.0.2'
Validating architecture
Validating architecture
Starting remote build
Compiling sources:
main.cpp
Linking objects
/usr/bin/ld : error : /home/pi/projects/cpp_raspbian_thread_101/obj/ARM/Debug/main.o: in function `std::thread::thread<void (&)(), , void>(void (&)())':
/usr/include/c++/8/thread(135): error : undefined reference to `pthread_create'
collect2 : error : ld returned 1 exit status
So I'm back to the pthread_create problem again
OK both code examples now compile and run.
As I originally thought, I needed to add -pthread somewhere in VS2019 and I was putting it in the wrong section.
Go to
Project Properties > Configuration Properties > Linker > Command Line
Add -pthread to Additional Options box and Apply.
I hope that saves someone else the 3 days it took me to sort it!
I'm learning about pthread_cond_t and wrote the following code intended to block forever at the pthread_cond_wait():
// main.cpp
// Intentionally blocks forever.
#include <iostream>
#include <cstring>
#include <cerrno>
#include <pthread.h>
int main( int argc, char* argv[] )
{
pthread_cond_t cond;
if ( pthread_cond_init( &cond, NULL ) )
{
std::cout << "pthread_cond_init() failed: " << errno << "(" << strerror( errno ) << ")" << std::endl;
}
pthread_mutex_t mutex;
if ( pthread_mutex_init( &mutex, NULL ) )
{
std::cout << "pthread_mutex_init() failed: " << errno << "(" << strerror( errno ) << ")" << std::endl;
}
pthread_mutex_lock( &mutex );
pthread_cond_wait( &cond, &mutex );
pthread_cond_destroy( &cond );
return 0;
}
When I first compiled/executed this program, the executable did not hang - it exited:
>g++ --version
g++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-7)
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
>g++ -g main.cpp && ./a.out
> // <-- Note: returned to bash prompt
Next I tried linking against libpthread - and now the executable hung, as expected:
>g++ -g main.cpp -lpthread && ./a.out
^C
> // <-- Needed to send SIGINT to terminate process
I was actually expecting to hit a link error for the required pthread functions; why did I not encounter one when I did not explicitly link against libpthread?
This question may be rendered moot by the answer to the above, but when compiling without the explicit link the libpthread, why did the resulting binary "skip over" or ignore the pthead_cond_wait()? Is there some default do-nothing implementation for pthread functions in glibc or somewhere?
Some glibc functions need locking when your process is multithreaded.
To avoid dragging in the libpthread dependency everytime because of that, glibc uses weakrefs to refer to a bunch of pthread functionality. If it detects the functionality is not available (which won't cause a linker error because of the weakref solution) it will default those ops to no-ops (which is just fine because if you don't have pthreads, you can't be multithreaded and locking isn't needed).
The upshot of this solution is the behavior you're getting.
I have a problem with curlpp library. I'll explain the steps that I followed.
Step 1: download and installation
download website: Download
$./configure
$make
$sudo make install
curlpp header files are located in /usr/local/include/
curlpp library files are located in /usr/local/lib/
Step 2: I used the following code:
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <curlpp/Exception.hpp>
using namespace std;
int main()
{
char *url = (char*) "http://dbpedia.org/sparql";
string queryString = "PREFIX dbp: <http://dbpedia.org/resource/> "
"PREFIX dbp2: <http://dbpedia.org/ontology/> "
"SELECT ?abstract "
"WHERE { "
"dbp:Nikola_Tesla dbp2:abstract ?abstract . "
"FILTER langMatches(lang(?abstract), 'en')"
"}";
try
{
curlpp::Easy request;
string parameters = "query=" + curlpp::escape(queryString);
request.setOpt(new curlpp::options::Url(url));
request.setOpt(new curlpp::options::Verbose(true));
request.setOpt(new curlpp::options::PostFields(parameters));
request.perform();
}
catch (curlpp::RuntimeError & e)
{
std::cout << e.what() << std::endl;
}
catch (curlpp::LogicError & e)
{
std::cout << e.what() << std::endl;
}
return 0;
}//end function main
Errors
Undefined reference to curlpp ::Easy:Easy()
Undefined reference to curlpp ::escape (const std :: string &)
Undefined reference to curlpp ::Easy::setopt (curlpp OptionBase :: *)
Undefined reference to curlpp curlpp::Easy::setopt(curlpp OptionBase:: *)
etc.
After adding -lcurlpp as the picture shows: I got the following errors:
g++ -LSQLiteCpp-master/debug -o bin/Debug/EntityLinking
obj/Debug/DataLoader.o obj/Debug/Entity.o obj/Debug/Fact.o
obj/Debug/FactClass.o obj/Debug/Link.o obj/Debug/main.o
obj/Debug/ManageDb.o obj/Debug/SQLiteCpp-master/sqlite3/sqlite3.o
obj/Debug/tinyxml/tinystr.o obj/Debug/tinyxml/tinyxml.o
obj/Debug/tinyxml/tinyxmlerror.o obj/Debug/tinyxml/tinyxmlparser.o
-lpthread -ldl -lcurlpp SQLiteCpp-master/debug/libSQLiteCpp.a /usr/bin/ld: obj/Debug/main.o: référence au symbole non défini
«curl_easy_setopt##CURL_OPENSSL_3»
//usr/lib/x86_64-linux-gnu/libcurl.so.4: error adding symbols: DSO
missing from command line collect2: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s)) 0
error(s), 0 warning(s) (0 minute(s), 0 second(s))
You need to link with -lcurlpp when compiling & linking your code.
Using Eclipse, I never got curlpp example01 working. Even after trying to set up the linkers and the includes. But I was able to compile it from a terminal:
g++ -o exe_name exe_name.cpp -L/usr/local/lib -lcurl -lcurlpp -I/usr/local/include
So I would suggest trying the terminal if Eclipse doesn't work for you.
I am running a beaglebone and want to write a program to sample the ADC. I am trying to use the blacklib (http://blacklib.yigityuce.com/index.html) from here. I cloned the git:
https://github.com/yigityuce/BlackLib
and tried to compile the example with
g++ exampleAndTiming.cpp -std=c++11
This however gives me a ton of errors like these:
In file included from exampleAndTiming.cpp:33:0:
exampleAndTiming/exampleAndTiming_GPIO.h: In function 'void exampleAndTiming_GPIO()':
exampleAndTiming/exampleAndTiming_GPIO.h:97:12: error: 'sleep' was not declared in this scope
sleep(1);
^
In file included from exampleAndTiming.cpp:34:0:
exampleAndTiming/exampleAndTiming_ADC.h: In function 'void exampleAndTiming_ADC()':
exampleAndTiming/exampleAndTiming_ADC.h:67:16: error: 'usleep' was not declared in this scope
usleep(1000);
^
so I include unistd.h (in exampleAndTiming.cpp), but then I get errors like these:
/tmp/ccbgiXE9.o: In function `exampleAndTiming_GPIO()':
exampleAndTiming.cpp:(.text+0x50): undefined reference to `Timing::startMeasure(std::string)'
exampleAndTiming.cpp:(.text+0x80): undefined reference to `BlackLib::BlackGPIO::BlackGPIO(BlackLib::gpioName, BlackLib::direction, BlackLib::workingMode)'
exampleAndTiming.cpp:(.text+0xbc): undefined reference to `Timing::endMeasure(std::string)'
exampleAndTiming.cpp:(.text+0xec): undefined reference to `BlackLib::BlackGPIO::BlackGPIO(BlackLib::gpioName, BlackLib::direction, BlackLib::workingMode)'
exampleAndTiming.cpp:(.text+0x104): undefined reference to `BlackLib::BlackGPIO::BlackGPIO(BlackLib::gpioName, BlackLib::direction, BlackLib::workingMode)'
exampleAndTiming.cpp:(.text+0x11c): undefined reference to `BlackLib::BlackGPIO::BlackGPIO(BlackLib::gpioName, BlackLib::direction, BlackLib::workingMode)'
exampleAndTiming.cpp:(.text+0x158): undefined reference to `Timing::startMeasure(std::string)'
I've been looking at some library examples and compiling it, but I cannot make sense of it all. I've compiled plenty of c++ and c programs before, but I can't get this one to work. So any help will be appreciated.
COMPLETE GUIDE how to compile BLACKLIB directly on BEAGLEBONE BLACK (rev C) running ANGSTROM:
Programs:
Putty - to communicate with BBB from Windows (using SSH with USB cable)
WinSCP - to manage (upload, create, delete) files directly on BBB
Code::Blocks - to write C++ programs
optionally
Termite 2.9 - to send and receive UART transmission from UART<->USB converter (actually Putty could be used to do that as well)
1) get the BlackLib from official site
2) unzip the library and copy following files into separate folder :
BlackADC.cpp, BlackADC.h, BlackCore.cpp, BlackCore.h, BlackDef.h, BlackErr.h, BlackGPIO.cpp, BlackGPIO.h, BlackI2C.cpp, BlackI2C.h, BlackLib.h, BlackPWM.cpp, BlackPWM.h, BlackSPI.cpp, BlackSPI.h, BlackUART.cpp, BlackUART.h
3) open following files in Code::Blocks BlackUART.cpp, BlackSPI.cpp, BlackI2C.cpp and add
#include <unistd.h>
right after #include "BlackUART.h", the "unistd.h" includes all the functions like sleep(), open(), close(), ... that otherwise seems missing
4) create your own program main.cpp, you may use the following code for testing UART1 and UART2:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sstream>
#include <string>
#include <iostream>
#include "BlackLib.h"
int main(){
std::string writeToUart1;
std::string writeToUart2;
std::string readFromUart1;
std::string readFromUart2;
int counter;
std::ostringstream os1;
std::ostringstream os2;
BlackLib::BlackUART Uart1(BlackLib::UART1,
BlackLib::Baud9600,
BlackLib::ParityEven,
BlackLib::StopOne,
BlackLib::Char8 );
// Pins on BeagleBone Black REV C
// UART1_RX -> GPIO_15 (P9.24)
// UART1_RX -> GPIO_14 (P9.26)
BlackLib::BlackUART Uart2(BlackLib::UART2,
BlackLib::Baud9600,
BlackLib::ParityEven,
BlackLib::StopOne,
BlackLib::Char8 );
// Pins on BeagleBone Black REV C
// UART2_RX -> GPIO_2 (P9.22)
// UART2_RX -> GPIO_3 (P9.21)
std::cout << "Program UART start" << std::endl << std::flush;
Uart1.open( BlackLib::ReadWrite | BlackLib::NonBlock );
Uart2.open( BlackLib::ReadWrite | BlackLib::NonBlock );
counter = 0;
while (true){
os1.str("");
os1.clear();
os1 << "Uart1 to TX: " << counter << "\n";
writeToUart1 = os1.str();
Uart1 << writeToUart1;
readFromUart1 = "";
Uart1 >> readFromUart1;
if (readFromUart1.compare("") != 0){
std::cout << "Uart1 from RX: " << readFromUart1 << "\n" << std::flush;
}
Uart1.flush( BlackLib::bothDirection );
counter++;
sleep(2);
os2.str("");
os2.clear();
os2 << "Uart2 to TX: " << counter << "\n";
writeToUart2 = os2.str();
Uart2 << writeToUart2;
readFromUart2 = "";
Uart2 >> readFromUart2;
if (readFromUart2.compare("") != 0){
std::cout << "Uart2 from RX: " << readFromUart2 << "\n" << std::flush;
}
Uart2.flush( BlackLib::bothDirection );
counter++;
sleep(2);
}
return 1;
}
5) save the main.cpp to the same folder as the BlackLib files
6) using WinSCP, create directory on the BBB (e.g. /home/uart) and copy all the BlackLib files and main.cpp into this folder
7) open Putty and navigate to the folder by :
cd /home/uart
8) compile the files by using :
gcc *.cpp -o main -std=c++11
9) run the program :
./main
10) connect the wires to UART<->USB converter and BBB. The ouput from BBB should look like :
Uart2 to TX: 1 OR Uart1 to TX: 0
Uart2 to TX: 3 OR Uart1 to TX: 2
depending on connection of wires
It seems I managed to fix it myself, some nooblike behaviour not including all the cpp files, but even more, I also needed to add #include to BlackCore.h to avoid tons of undefined function errors.
final command:
g++ exampleAndTiming.cpp exampleAndTiming/Timing.cpp BlackADC.cpp BlackCore.cpp BlackGPIO.cpp BlackI2C.cpp BlackPWM.cpp BlackSPI.cpp BlackUART.cpp -std=c++11
I'd probably need to make a makefile to compile the library seperately, time to do some more digging and learning.
I am the creator of BlackLib, Yiğit YÜCE. You found your answer by yourself. The makefile which you mentioned on your comment will be published shortly.
Maybe this questions is easy but I can't figure it out how to resolve it:
I try to compile an example which has pthreas on windows 7 (64bit), with Code Blocks I downloaded the prebuild library and set up building_options: the path for the compiler pthreadLib\include and the linker to pthreadLib\lib\x64
The program is:
extern "C"
{
#include <pthread.h>
#include <unistd.h>
}
#include <iostream>
#include <windows.h>
using namespace std ;
void * function1(void * argument);
void * function2(void * argument);
int main( void )
{
pthread_t t1, t2 ; // declare 2 threads.
pthread_create( &t1, NULL, function1,NULL); // create a thread running function1
pthread_create( &t2, NULL, function2,NULL); // create a thread running function2
Sleep(1);
return 0;
}
void * function1(void * argument)
{
cout << " hello " << endl ;
Sleep(2); // fall alseep here for 2 seconds...
return 0;
}
void * function2(void * argument)
{
cout << " world " << endl ;
return 0;
}
In case I comment pthread_create(); function, than it builds. So pthread_t is recognized as a type.
When I try to compile with pthread_create I get an error:
mingw32-g++.exe -L..\libs\Pre-built.2\lib\x64 -LD:\DropBox\WorkUT\Programs\MyODP\libs -o bin\Release\RIP.exe obj\Release\main.o -s ..\libs\Pre-built.2\lib\x64\libpthreadGC2.a ..\libs\Pre-built.2\lib\x64\pthreadVC2.lib
obj\Release\main.o:main.cpp:(.text.startup+0x36): undefined reference to `_imp__pthread_create'
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
1 error(s), 1 warning(s) (0 minute(s), 0 second(s))
Do I have to make additional setups in C::B? I tired to add the linker command -lpthread but is not recognized.
After 2 days I figured it out.
First: I installed the minGW 64 for Windows OS.
Next: I set up C::B to use the minGW_64 after this post.
Moreover: I added to the linker libs ..\libs\Pre-built.2\lib\x64\libpthreadGC2.a and ..\libs\Pre-built.2\lib\x64\pthreadVC2.lib. Finally, I added to my project the pthreadGC2.dll (64bit version!).
Lesson learned, don't mix lib. and compiler with 86 and 64.
For Linux
Use sleep(1) in stead of Sleep(1)