Issue with boost library linking in c++ - c++

problem with implementing the time based event "validate", like wait methode takes the current time and time after 1 hour and sleep for 1 hour then calling this validate function.
but when i run this code it shows error
boost library version is: 1.71
In main.cpp i am trying to make the two touch file and clock and synchronize, then implement the get_latest_clock_entry which print the last modified time of the clock file. and then wait function waits for 1 hour and run the validate function. wait function should invokes the validates methode every hour.
main.cpp
#include <iostream>
#include <fstream>
#include <time.h>
#include <sys/stat.h>
#include <boost/date_time.hpp>
#include <boost/thread/thread.hpp>
using namespace std;
constexpr char clock_file[] = "/home/saman/Desktop/clock";
constexpr char sync_file[] = "/home/saman/Desktop/synchronized";
class TimeEvent {
public:
void receive_time_event(timespec& time) {
// Create clock file
ofstream clockFile(clock_file);
if (!clockFile.is_open()) {
cout << "Failed to open file" << endl;
}
clockFile.close();
// Create synchronized file
ofstream synchronizedFile(sync_file);
if (!synchronizedFile.is_open()) {
cout << "Failed to open file" << endl;
}
synchronizedFile.close();
}
timespec get_latest_clock_entry(){
string clockFilePath = clock_file;
struct stat fileStat;
if(stat(clockFilePath.c_str(), &fileStat) == 0){
time_t mtime = fileStat.st_mtime;
timespec time;
time.tv_sec = mtime;
time.tv_nsec = 0;
char timeString[50];
strftime(timeString, sizeof(timeString), "%Y-%m-%d %H:%M:%S", gmtime(&time.tv_sec));
cout << "Last modified time "<< clockFilePath << " : " << timeString << endl;
return time;
}
else{
cout << "Can't retrieve last modified time " << clockFilePath << endl;
return {0,0};
}
}
void wait(){
boost::posix_time::ptime timeLocal = boost::posix_time::second_clock::local_time();
cout << "Now Time" << timeLocal << endl;
boost::posix_time::ptime counter = timeLocal + boost::posix_time::hours(1);
cout << "update Time" << timeLocal << endl;
boost::this_thread::sleep(counter);
}
void validate(){
cout << "hi" << endl;
}
};
int main() {
TimeEvent timeEvent;
timespec time;
timespec_get(&time, TIME_UTC);
timeEvent.receive_time_event(time);
auto lastModifiedTime = timeEvent.get_latest_clock_entry();
while(1){
timeEvent.wait();
timeEvent.validate();
}
return 0;
}
Error:
/usr/bin/ld: /tmp/ccJEJpvk.o: in function `boost::condition_variable::condition_variable()':
2.cpp:(.text._ZN5boost18condition_variableC2Ev[_ZN5boost18condition_variableC5Ev]+0xc5): undefined reference to `pthread_condattr_setclock'
/usr/bin/ld: /tmp/ccJEJpvk.o: in function `boost::detail::interruption_checker::interruption_checker(pthread_mutex_t*, pthread_cond_t*)':
2.cpp:(.text._ZN5boost6detail20interruption_checkerC2EP15pthread_mutex_tP14pthread_cond_t[_ZN5boost6detail20interruption_checkerC5EP15pthread_mutex_tP14pthread_cond_t]+0x29): undefined reference to `boost::detail::get_current_thread_data()'
/usr/bin/ld: /tmp/ccJEJpvk.o: in function `boost::condition_variable::do_wait_until(boost::unique_lock<boost::mutex>&, boost::detail::mono_platform_timepoint const&)':
2.cpp:(.text._ZN5boost18condition_variable13do_wait_untilERNS_11unique_lockINS_5mutexEEERKNS_6detail23mono_platform_timepointE[_ZN5boost18condition_variable13do_wait_untilERNS_11unique_lockINS_5mutexEEERKNS_6detail23mono_platform_timepointE]+0x135): undefined reference to `boost::this_thread::interruption_point()'
collect2: error: ld returned 1 exit status
Update:
after compiling with g++ -o main main.cpp -lpthread
/usr/bin/ld: /tmp/cccOLyt1.o: in function `boost::detail::interruption_checker::interruption_checker(pthread_mutex_t*, pthread_cond_t*)':
2.cpp:(.text._ZN5boost6detail20interruption_checkerC2EP15pthread_mutex_tP14pthread_cond_t[_ZN5boost6detail20interruption_checkerC5EP15pthread_mutex_tP14pthread_cond_t]+0x29): undefined reference to `boost::detail::get_current_thread_data()'
/usr/bin/ld: /tmp/cccOLyt1.o: in function `boost::condition_variable::do_wait_until(boost::unique_lock<boost::mutex>&, boost::detail::mono_platform_timepoint const&)':
2.cpp:(.text._ZN5boost18condition_variable13do_wait_untilERNS_11unique_lockINS_5mutexEEERKNS_6detail23mono_platform_timepointE[_ZN5boost18condition_variable13do_wait_untilERNS_11unique_lockINS_5mutexEEERKNS_6detail23mono_platform_timepointE]+0x135): undefined reference to `boost::this_thread::interruption_point()'
collect2: error: ld returned 1 exit status

You need to link against both boost_thread and pthread.
$ g++ boost.cpp -o boost -lboost_thread -lpthread
$ ldd ./boost
linux-vdso.so.1 (0x00007ffc1bd79000)
libboost_thread.so.1.71.0 => /lib/x86_64-linux-gnu/libboost_thread.so.1.71.0 (0x00007fc4b7a51000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fc4b7a2e000)
libstdc++.so.6 => /lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fc4b784c000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fc4b7831000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fc4b763f000)
/lib64/ld-linux-x86-64.so.2 (0x00007fc4b7aee000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fc4b74f0000)
$ ./boost
Failed to open file
Failed to open file
Can't retrieve last modified time /home/saman/Desktop/clock
Now Time2023-Jan-19 03:43:47
update Time2023-Jan-19 03:43:47
hi
FYI first you have to find what is missing, in this case boost::detail::get_current_thread_data.
Use the line below
$ find /usr/lib -name 'libboost*' | xargs -i /bin/bash -x -c "nm -C {}" | grep boost::detail::get_current_thread_data
Then look for the line that has the status "T" after the address. The library above it is the one that you need to include.
+ nm -C /usr/lib/x86_64-linux-gnu/libboost_thread.a
0000000000000210 T boost::detail::get_current_thread_data()

You need to link with Boost.Thread library. For example, if you're using clang or gcc, add -lboost_thread to your compiler command line.

Related

Linker cannot find local shared library

I'm trying a very simple exmaple to create a shared library and link to it. The shared library is as follows:
#ifndef ARDUGRAB_H_
#define ARDUGRAB_H_
#include <iostream>
using namespace std;
namespace ArduGrabLibrary{
class ArduGrab{
public:
ArduGrab();
virtual void initCamera();
virtual void setSim(bool sim);
virtual void setDebug(bool debug);
private:
bool debug = false;
bool sim = false;
};
}
Then the source code file is just as simple:
#include "ardugrab.h"
namespace ArduGrabLibrary
{
ArduGrab::ArduGrab(){
std::cout << "IMX298 Constructor" << std::endl;
}
void ArduGrab::initCamera(){
if (this->debug){
cout << "init camera" << std::endl;
}
}
void ArduGrab::setSim(bool sim){
this->sim = sim;
if (this->debug){
cout << "set sim to " << std::boolalpha << this->sim << std::endl;
}
}
void ArduGrab::setDebug(bool debug){
this->debug = debug;
if (this->debug){
cout << "set debug to " << std::boolalpha << this->sim << std::endl;
}
}
}
I'm then compiling that into a shared library with:
g++ -fPIC -shared -o ardugrab.so ardugrab.cpp
All good, we get an ardgrab.so library so to test it, with the following code in teh same directory as the .so and .h files from above:
#include "ardugrab.h"
using namespace ArduGrabLibrary;
int main() {
std::cout << "starting program" << std::endl;
ArduGrab* ardu = new ArduGrab();
ardu->setDebug(true);
//imx298->setSim(true);
//imx298->initCamera();
return 0;
}
So now we need to compile this into an executable with:
g++ -L. -lardugrab -o testardugrab testardugrab.cpp
This however fails to find the ardugrab.so file, the follow error message appears:
pi#raspberrypi:~/ArduMipiGrab $ g++ -L. -lardugrab -o testardugrab testardugrab.cpp
/usr/bin/ld: cannot find -lardugrab
collect2: error: ld returned 1 exit status
I've tried setting LD_LIBRARY_PATH to . export LD_LIBRARY_PATH=. but still nothing.
As you can see I'm a bit new with compiling c++, can someone please advise me as to what I'm doing wrong?
Thanks.
Reagrds,
Neil
This is becuase you are using the -l flag.
When you use this flag (Rather than specify a library specifically) it assumes a certain naming convention.
-lX
The linker assumes the file name is
libX.so (or libX.a)
So the commands you want are:
> g++ -fPIC -shared -o libardugrab.so ardugrab.cpp
> # ^^^
> g++ -L. -lardugrab -o testardugrab testardugrab.cpp
Note: The environment variable LD_LIBRARY_PATH is used at runtime when the standard library tries to find and load required shared libraries. I.E. it is not used during compilation to find shared libraries to link with.

/usr/bin/ld: /tmp/cc9zxSDP.o: undefined reference to symbol

The following compile error i am facing when i compile a .cc file. i am using apache ignite libraries and c++ libraries to compile and jdk path is specified.
#include <iostream>
#include "ignite/ignite.h"
#include "ignite/ignition.h"
using namespace ignite;
using namespace cache;
int main()
{
IgniteConfiguration cfg;
cfg.jvmInitMem = 512;
cfg.jvmMaxMem = 512;
cfg.springCfgPath = "/home/ignite/DataGridTest.xml";
try
{
Ignite grid = Ignition::Start(cfg);
std::cout << std::endl;
std::cout << ">>> Cache put-get example started." << std::endl;
std::cout << std::endl;
Cache<int, int> cache = grid.GetCache<int, int>("mycache");
cache.Clear();
cache.Put(1, 1);
int orgFromCache = cache.Get(1);
std::cout << ">>> Retrieved value from cache: " << std::endl;
std::cout << orgFromCache << std::endl;
std::cout << std::endl;
Ignition::StopAll(false);
}
catch (IgniteError& err)
{
std::cout << "An error occurred: " << err.GetText() << std::endl;
}
std::cout << std::endl;
std::cout << ">>> Example finished, press 'Enter' to exit ..." << std::endl;
std::cout << std::endl;
return 0;
}
In command line:
gcc -I /usr/java/jdk1.8.0_131/include/ -I
/usr/java/jdk1.8.0_131/include/linux/ -I
$IGNITE_HOME/platforms/cpp/jni/include/ -I
$IGNITE_HOME/platforms/cpp/core/include/ -I
$IGNITE_HOME/platforms/cpp/common/os/linux/include/ -I
$IGNITE_HOME/platforms/cpp/examples/include/ DataGridTest.cc -o DataGridTest -lignite
/usr/bin/ld: /tmp/cc9zxSDP.o: undefined reference to symbol '_ZN6ignite3jni4java12JniErrorInfoD1Ev'
/usr/local/lib//libignite-jni-2.0.0.19668.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
Except for the libignite you also need to link to libignite-binary, libignite-common and libignite-jni.

Compilation issue while using Folly Futures

#include <folly/futures/Future.h>
#include<iostream>
using namespace folly;
using namespace std;
void foo(int x)
{
// do something with x
cout << "foo(" << x << ")" << endl;
}
// ...
int main()
{
cout << "making Promise" << endl;
Promise<int> p;
Future<int> f = p.getFuture();
return 0;
}
LD_LIBRARY_PATH is set to /usr/local/lib
When I compile, using
g++ -std=c++11 sample.cpp -pthread -llzma -lz -lsnappy -llz4 -liberty \
-ljemalloc -levent -ldouble-conversion -lssl -lgflags -lglog -lboost_system
I get this error message:
/tmp/ccuDCM19.o: In function `main':
sample.cpp:(.text+0x1a7): undefined reference to `folly::Future<int>::~Future()'
/tmp/ccuDCM19.o: In function `folly::RequestContext::setContext(std::shared_ptr<folly::RequestContext>)':
sample.cpp:(.text._ZN5folly14RequestContext10setContextESt10shared_ptrIS0_E[_ZN5folly14RequestContext10setContextESt10shared_ptrIS0_E]+0x11): undefined reference to `folly::RequestContext::getStaticContext()'
/tmp/ccuDCM19.o: In function `folly::Promise<int>::getFuture()':
sample.cpp:(.text._ZN5folly7PromiseIiE9getFutureEv[_ZN5folly7PromiseIiE9getFutureEv]+0x36): undefined reference to `folly::Future<int>::Future(folly::detail::Core<int>*)'
collect2: error: ld returned 1 exit status
Issue got resolved by adding -lfolly.

C++ error: undefined reference to function

I have three files:
Two .cpp files (Reader.cpp and algo.cpp) and one header file (algo.h).
In Reader.cpp file, its function PacketHandler calls a function present in algo.cpp.
Reader.cpp
void PacketHandler(Packet* sniff_packet, void* user) {
std::string payload;
RawLayer* raw_payload = sniff_packet->GetLayer<RawLayer>();
if (raw_payload) {
/* Summarize some data */
cout << "[+] ------- [+]" << endl;
TCP* tcp_layer = sniff_packet->GetLayer<TCP>();
cout << "[#] TCP packet from source port: " << dec << tcp_layer->GetSrcPort() << endl;
cout << "[#] With Payload: " << endl;
payload = raw_payload->GetStringPayload();
SPPM(payload); // Function present in algo.cpp
}
}
void main() { // }
algo.h
#ifndef algo_H_
#define algo_H_
#include <string>
using namespace std;
void SPPM (std::string input);
#endif
algo.cpp
#include "algo.h"
#define byte uint8_t
using namespace std;
void SPPM(std::string input){ //definition }
When I compile the code using g++, I get this error:
In function `PacketHandler(Crafter::Packet*, void*)':
/home/maleeha/libcrafter_latest/libcrafter-master/libcrafter/pcap_reader.cpp:32: undefined reference to `SPPM(std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'collect2: ld returned 1 exit status
I am executing my code this way:
g++ -c Reader.cpp -o Reader.o -g -lcrafter
g++ -c algo.cpp -o algo.o
g++ -o program Reader.o algo.o -lcrafter
./program Packets.pcap
Why is this error coming?

Linker error compiling keyczar program

I am using g++ -lkeyczar -lcrypto -o basic_encrypt -Wall -O2 base_encrypt.cpp to compile the following code:
#include <cassert>
#include <iostream>
#include <string>
#include <keyczar/keyczar.h>
void EncryptAndDecrypt(const std::string& location) {
keyczar::Keyczar* crypter = keyczar::Crypter::Read(location);
if (!crypter)
return;
std::string input = "Secret message";
std::string ciphertext;
std::cout << "Plaintext: " << input << std::endl;
bool result = crypter->Encrypt(input, &ciphertext);
if (result) {
std::cout << "Ciphertext (Base64w): " << ciphertext << std::endl;
std::string decrypted_input;
bool result = crypter->Decrypt(ciphertext, &decrypted_input);
if (result)
assert(input == decrypted_input);
}
delete crypter;
}
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "An absolute key set location must be provided as argument"
<< std::endl;
return 1; // error
}
// The first argument must represent the keyset's location
const std::string location(argv[1]);
EncryptAndDecrypt(location);
return 0;
}
Which is a tutorial taken from here
However, I am running into the following error:
/tmp/ccNlack3.o: In function `EncryptAndDecrypt(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)':
base_encrypt.cpp:(.text+0xf): undefined reference to `keyczar::Crypter::Read(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)'
collect2: ld returned 1 exit status
I am unable to solve this since I know that I am already giving the library flags while compiling. Why is it still unable to link correctly ?
Put the library flags at the end of the command line:
g++ -o basic_encrypt -Wall -O2 base_encrypt.cpp -lkeyczar -lcrypto