Vector of threads in C++ - c++

I am trying to use a vector of threads. I will receive an int as a parameter, which will be the number of threads I will have to create.
I tried something like this:
#include <iostream>
#include <thread>
#include <vector>
void credo()
{
std::cout << "threads" << std::endl;
}
void threads_creation()
{
int i;
std::vector<std::thread> threads_tab;
i = 0;
while(i < 2)
{
threads_tab.push_back(std::thread(credo));
i++;
}
}
int main()
{
threads_creation();
return (0);
}
But I get this compilation error:
/tmp/ccouS4PY.o: In function `std::thread::thread<void (&)()>(void (&)())':
threads.cpp:(.text._ZNSt6threadC2IRFvvEJEEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEEEOT_DpOT0_]+0x21): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
by compiling using the following command:
g++ -W -Wall -Werror -Wextra threads.cpp
What's wrong here?

The std::thread class utilizes pthreads in Linux, so you need to add the -pthread compiler flag to your command;
g++ -W -Wall -Werror -Wextra -pthread threads.cpp

Related

C++ Boost Example: Creating and Managing Threads (Compilation Error)

I am currently using Boost 1.54.0. I am following the code from this example.
example_44_01.cpp
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <iostream>
void wait(int seconds)
{
boost::this_thread::sleep_for(boost::chrono::seconds{seconds});
}
void thread()
{
for (int i = 0; i < 5; ++i)
{
wait(1);
std::cout << i << std::endl;
}
}
int main(int argc, char** argv)
{
boost::thread t{thread};
t.join();
return 0;
}
So, it looks like all I need is the -lboost_thread, and -lboost_chrono libraries to link to at compile time. I also added the -lboost_system.
Here are my execution scripts.
g++-7 -Wall -std=c++1z -g -c example_44_01.cpp -o example_44_01.o
g++-7 -Wall -std=c++1z -g example_44_01.o -o example_44_01 -lboost_system -lboost_thread -lboost_chrono &>result.txt
What's going on here? This is the result.txt file:
example_44_01.o: In function `boost::this_thread::sleep_for(boost::chrono::duration<long, boost::ratio<1l, 1000000000l> > const&)':
/usr/local/include/boost/thread/pthread/thread_data.hpp:243: undefined reference to `boost::this_thread::hidden::sleep_for(timespec const&)'
collect2: error: ld returned 1 exit status
I've compiled and linked other programs with the same libraries without error. So is the error in the code? This seems doubtful as the code is straight from the documentation. Any insight is appreciated.
I had this issue once because I was indeliberately using different versions of Boost (I had first installed Boost from commandline, then a few months later on, manually from zip).
Try adding the path to your Boost libraries to the compiler. For instance, if your libraries are stored at /usr/local/lib, try:
g++-7 -Wall -std=c++1z -g example_44_01.o -o example_44_01 -L/usr/local/lib -lboost_system -lboost_thread -lboost_chrono &>result.txt

Issue with std::thread from c++11

I have some troubles trying to compile a program with multi-threading from the standard template library.
It return me a obscure error when i try to compile the following program :
#include <iostream>
#include <thread>
void foo()
{
std::cout << "Thread 1\n";
}
int main(int argc, char** argv)
{
std::thread tr(foo);
std::cout << "Main thread\n";
tr.join();
return 0;
}
I don't understand the error :
/tmp/ccE8EtL1.o : In the function « std::thread::thread<void (&)()>(void (&)()) » :
file.cpp:(.text._ZNSt6threadC2IRFvvEJEEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEEEOT_DpOT0_]+0x21) : undefined reference to « pthread_create »
collect2: error : ld has return 1 execution status code
I compile it with :
g++ -std=c++14 file.cpp -o test -Wall
Can anyone help me please ?
Pass -pthread to the compiler. This flag combines what is necessary to compile and link the pthread library (-lpthread is not always enough). See this question.

undefined reference to `json11::Json::dump(std::string&) const' collect2: error: ld returned 1 exit status

I using json11 in my project
#include "crow_all.h"
#include "sqlOperations/sqlcpp_db_connection.cpp"
#include "date.h"
#include <json11.hpp>
int main() {
crow::SimpleApp app;
CROW_ROUTE(app,"/navOfFund")
.methods("POST"_method)
([](const crow::request& req){
auto x = crow::json::load(req.body);
if (!x)
return crow::response(400);
auto name = x["fund_name"].s();
std::ostringstream os;
vector<double>nav = select_from_fund_type(name);
json11::Json json(nav);
//std::cout << json.dump() << std::endl;
return crow::response{json.dump()};
});
crow::logger::setLogLevel(crow::LogLevel::Debug);
app.port(18080).multithreaded().run();
return 0;
}
And i am compiling my project using below command
g++ -std=c++1y -L/usr/local/lib -I ../../date main.cpp -ljson11 -lsqlpp-mysql -lmysqlclient -lboost_system -lpthread
And the error is
/tmp/ccqQDgWQ.o: In function `json11::Json::dump() const':
main.cpp:(.text._ZNK6json114Json4dumpEv[_ZNK6json114Json4dumpEv]+0x2c): undefined reference to `json11::Json::dump(std::string&) const'
collect2: error: ld returned 1 exit status
I am not able to find the root cause of error.
But i don't know why, this works perfectly fine.
#include <iostream>
#include <json11.hpp>
int main()
{
std::vector<double> test_vector { 0.1, 0.2, 0.3, 0.4, 0.5 };
json11::Json json(test_vector);
std::cout << json.dump() << std::endl;
}
And compiling using
g++ -std=c++1y json_test.cpp -ljson11
The function void dump(std::string &out) isn't defined in the .hpp file, see here.
Instead it is defined in the .cpp file, that is here.
You should rather do this:
g++ -std=c++1y -L/usr/local/lib -I ../../date main.cpp json11.cpp -lsqlpp-mysql -lmysqlclient -lboost_system -lpthread

g++ link error: 'undefined reference to 'main'

I have 3 files; main.cpp (which contains main()), FileWriter.h, and FileWriter.cpp. I'm using g++ (version Debian 4.9.2-10) on Debian Jessie. My project contains .cpp files in '/root/dev/Practice/src/', and a single header (FileWriter.h) in '/root/dev/Practice/include/'. The compilation of the two object files works, but the linking to an executable complains about undefined reference to main(), although I do indeed have a seemingly valid one defined in 'main.cpp'.
Here's the output of my make file (which is in the root '/root/dev/Practice/' directory):
g++ -c -g -Wall -o src/FileWriter.o src/FileWriter.cpp
g++ -c -g -Wall -o src/main.o src/FileWriter.cpp
g++ src/FileWriter.o src/main.o -o bin/Practice
/usr/lib/gcc/i586-linux-gnu/4.9/../../../i386-linux-gnu/crt1.o: In function '_start'"
/build/glibc-J1NNmk/glibc-2.19/csu/../sysdeps/i386/start.S:111: undefined reference to 'main'
collect2: error: ls returned 1 exit status
Makefile:10: recipe for target 'bin/Practice' failed
Here's the contents of my main.cpp file:
#include <string>
#include <iostream>
#include "/root/dev/Practice/include/FileWriter.h"
int main() {
std::cout << "Hello!" << std::endl;
FileWriter * fw = new FileWriter("foofile");
fw->AddLine("CRAP!");
fw->AddLine("NO!");
return 0;
}
My FileWriter.h:
#ifndef FILEWRITER_H_
#define FILEWRITER_H_
#include <string>
#include <iostream>
class FileWriter{
public:
FileWriter(std::string);
~FileWriter();
void AddLine(std::string);
private:
std::string fileLocation;
std::ofstream *filestream;
};
#endif /* FILEWRITER_H_ */
...and my FileWriter.cpp:
#include "/root/dev/Practice/include/FileWriter.h"
#include <fstream>
// g++ linker error if 'inline' not included - why?
inline FileWriter::FileWriter(std::string fileName)
{
this->fileLocation = fileName;
const char * x = this->fileLocation.c_str();
this->filestream = new std::ofstream();
this->filestream->open(x, std::ios::out | std::ios::app);
}
inline FileWriter::~FileWriter()
{
this->filestream->close();
}
inline void FileWriter::AddLine(std::string line)
{
*this->filestream << line << std::endl;
}
This line:
g++ -c -g -Wall -o src/main.o src/FileWriter.cpp
should be:
g++ -c -g -Wall -o src/main.o src/main.cpp
I don't have access to this compiler, but in the past if you had main() in a C++ file you needed to "decorate" it with __cdecl
int __cdecl main() {
Try that? Or:
extern "C" int main() {

Undefined reference to vector declared in a different source file used in an "if" statement

I've created a source file that contains a number of data structures (maps, vector, array). Its header file is #included in the main-file.
The main file looks like this:
#include "reachability.h" //Where monkey() and vector<int> int_req are declared
main()
{
monkey(int_req); // Calling monkey(int_req) here is OK! Bar is visible
...
ifstream fp("foo.txt");
if(fp.is_open())
{
std::string line;
while( getline(fp,line) )
{
monkey(int_req); //'int_req' is an undefined reference!
}
}
}
And reachability.h
#ifndef REACHABILITY_H
#define REACHABILITY_H
extern std::vector<int> int_req;
void monkey(std::vector<int> feces);
#endif
And reachability.cc
std::vector<int> int_req;
void monkey(std::vector<int> thrown_obj)
{
... //Iteration and dereferencing of "thrown_obj"
}
I've accessed data structures that are declared in reachability.cc in a for-loop in the scope of main and that was fine. Something wonky is happening in this if-statement though.
Compiler Error:
lab1.o: In function `main':
/home/ubuntu/workspace/ECE597/Lab1/lab1.cc:105: undefined reference to `int_req'
collect2: error: ld returned 1 exit status
Edited: reachability.cc is included in compiliation:
elusivetau:~/XXXX/XXXX/XXXX $ g++ lab1.cc parser.cc gate.cc reachability.cc -o run
/tmp/ccJK4O9q.o: In function `main':
lab1.cc:(.text+0x489): undefined reference to `int_req'
collect2: error: ld returned 1 exit status
Edited: makefile for this program:
all: lab1.o parser.o gate.o reachability.o
g++ -g lab1.o parser.o gate.o reachability.o -o run
lab1.o: lab1.cc
g++ -g -c lab1.cc
parser.o: parser.cc
g++ -g -c parser.cc
gate.o: gate.cc
g++ -g -c gate.cc
reachability.o: reachability.cc
g++ -g -c reachability.cc
clean:
rm *o run
Whatever it is, you're not giving us the correct information.
I added includes and removed non-code to make this compile. And voila, it also links:
test.cpp:
#include "reachability.h" //Where monkey() and vector<int> int_req are declared
#include <string>
#include <iostream>
#include <fstream>
main()
{
monkey(int_req); // Calling monkey(int_req) here is OK! Bar is visible
std::ifstream fp("foo.txt");
if(fp.is_open())
{
std::string line;
while( getline(fp,line) )
{
monkey(int_req); //'int_req' is an undefined reference!
}
}
}
reachability.h:
#ifndef REACHABILITY_H
#define REACHABILITY_H
#include <vector>
extern std::vector<int> int_req;
void monkey(std::vector<int> feces);
#endif
reachability.cpp:
#include "reachability.h"
std::vector<int> int_req;
void monkey(std::vector<int> thrown_obj)
{
}
This compiles and links just fine. You are leading us on a wild goose chase by not bothering to create a mvce