I have been trying to get a program working in Eclipse C++. One of the functions uses multithreading from std. Here is the function in the code:
void PrimeCheck::checkFull(long long int number)
{
std::thread t1(&PrimeCheck::checkFirstHalf, this, number);
std::thread t2(&PrimeCheck::checkSecondHalf, this, number);
t1.join();
t2.join();
}
When searching for a solution, I came across many solutions, all of which stating to either add a -pthread flag or a -std=c++11 in addition to changing the dialect to C++11. All of which I have done. This is what the compile command looks like in eclipse so you can see exactly which modifications I have already added:
Building file: ../src/Prime Checker.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -D__GXX_EXPERIMENTAL_CXX0X__ -O2 -g -Wall -c -fmessage-length=0 -std=c++11 -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive -MMD -MP -MF"src/Prime Checker.d" -MT"src/Prime\ Checker.d" -o "src/Prime Checker.o" "../src/Prime Checker.cpp"
Finished building: ../src/Prime Checker.cpp
And this is the linker command as it appears in eclipse:
Invoking: GCC C++ Linker
g++ -Wl,--no-as-needed -pthread -shared -o [A bunch of .o files]
The code compiles correctly, and eclipse content assist recognizes thread as a member of std. Yet, when I run the program I still this error:
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
To test this, I wrote a simple program outside of Eclipse which looked like this:
#include <thread>
#include <iostream>
using namespace std;
void func1(int x){
for(int i=0; i<x; i++){
cout << " " << 1 + i;
}
}
void func2(){
for(int j=0; j<5; j++){
cout << "Standard message! ";
}
}
int main(){
int input;
cout << "Give me a number:" << endl;
cin >> input;
thread t1(func1, input);
thread t2(func2);
t1.join();
t2.join();
return 0;
}
And compiled it in the terminal with this:
g++ ThreadTest.cpp -o Program.o -std=c++11 -pthread
And the program ran without error. I think this means that there's something wrong with Eclipse, but I'm not sure.
As a note, I'm doing this on Ubuntu 14.04 with gcc version 4.8.4. Also, I know that similar questions have been asked, but as far as I can tell, I've implemented those solutions with little success.
Help would be appreciated. Thanks!
Solved. Using Eclipse IDE for C/C++ Developers v4.7.3a in Ubuntu 14.04.
1/2. Problem description
Just trying to run this sample code:
mutex.cpp:
// mutex example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
std::mutex mtx; // mutex for critical section
void print_block (int n, char c) {
// critical section (exclusive access to std::cout signaled by locking mtx):
mtx.lock();
for (int i=0; i<n; ++i) { std::cout << c; }
std::cout << '\n';
mtx.unlock();
}
int main ()
{
std::thread th1 (print_block,50,'*');
std::thread th2 (print_block,50,'$');
th1.join();
th2.join();
return 0;
}
From: http://www.cplusplus.com/reference/mutex/mutex/
It builds and runs just fine on the command line with the following command, but will not run in Eclipse!
Command-line command that builds and runs in a terminal just fine:
g++ -Wall -std=c++11 -save-temps=obj mutex.cpp -o ./bin/mutex -pthread && ./bin/mutex
Eclipse error when I try to run it in Eclipse:
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
2/2. The solution to make it build and run in Eclipse is as follows:
A. Enable pthread for compiler:
Project --> Properties --> C/C++ Build --> Settings --> GCC C++ Compiler --> Miscellaneious --> type in -std=c++11 to the "Other flags" box, and check the box for "Support for pthread (-pthread)". See yellow highlighting here:
B. Enable pthread for Linker:
Then, withOUT closing this window, also set this setting for the Linker:
in center pane: GCC C++ Linker --> General --> check the box for "Support for pthread (-pthread)", as shown here:
Click "Apply and Close". It will now build and run.
Related
I have been trying to compile and run the following very simple bit of code
#include <thread>
using namespace std;
void thread_c() {
for (int i = 0; i < 11; ++i) {
cout << i;
}
}
int main()
{
thread t(thread_c);
t.join();
system("pause");
return 0;
}
I am compiling on Windows 10 with MinGW 6.3.0 (target x86_64-w64-mingw32) and the thread model (obtained using g++ -v) is POSIX.
I am not getting any compilation error with g++ -Wall -g test.cpp -o test.exe, however I am getting a runtime error when trying to run the exe (entry point of _ZNSt6thread15_M_start_threadESt10unique_ptrINS_3_StateESt14default_deleteIS1_EEPFvve cannot be found).
I also tried compiling with the -pthreador -lpthread flags, but I am getting the same runtime error.
Obviously this seems to be related to the use of std::thread, but I didn't get how to fix this. Am I missing a compilation flag or additional library enabling POSIX thread support on Windows?
Edit: I managed to get it working by changing the compilation command to
g++ -Wall -g test.cpp -o test.exe -static-libgcc -static-libstdc++ -Wl,-Bstatic -lstdc++ -lpthread -Wl,Bdynamic
I tried your code after making the necessary fixes:
#include <thread>
#include <iostream>
using namespace std;
void thread_c() {
for (int i = 0; i < 11; ++i) {
std::cout << i;
}
}
int main()
{
thread t(thread_c);
t.join();
system("pause");
return 0;
}
and it worked fine.
The build command was the same as yours:
g++ -Wall -g test.cpp -o test.exe
The output was:
012345678910Press any key to continue . . .
But I did use MinGW-w64 GCC 12.1.0 (fro https://winlibs.com/) instead of the very old version 6.3.0.
Maybe the MinGW-w64 (or was it still the old MinGW) library you were using was simply too old...
I'm developing a library that works with std::jthread (new in C++20) using g++ 10.0.1. The library works fine if I compile it using share libraries, but If I compile it with static libraries I got a segmentation fault at the end of the program (thread destructor). I have narrowed down my test case to a simple thread creation and join:
#include <iostream>
#include <thread>
int main(int argc, const char** argv) {
auto t = std::jthread([]() { std::cout << "OK\n"; });
t.join();
return 0;
}
To compile I use:
g++-10 -o test --static -std=c++20 test.cc -lpthread
And running it:
% ./test
zsh: segmentation fault (core dumped) ./test
There any one has an idea what this problem could be?
Update:
Following #JérômeRichard suggested reference, I was able to compile and run my little test program without problem
g++-10 -o test --static -std=c++20 test.cc -lrt -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive
However, changing the code to use request_stop instead of join the program is segmenting fault again (https://godbolt.org/z/obGN8Y).
#include <iostream>
#include <thread>
int main() {
auto t = std::jthread([]{ std::cout << "OK" << std::endl; });
t.request_stop();
}
The problem was reported to libstdc++ (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95989) and a patch has been generated to solve the problem.
I have to debug a segfault in my C++ program using Code::Blocks.
Unfortunately, the stack trace isn't showing correctly, instead I see ?? ()
Here is a minimal example:
#include <iostream>
using namespace std;
int main()
{
int *plop;
cout << *plop << endl;
return 0;
}
The debugger says:
Program received signal SIGSEGV, Segmentation fault. In ?? () ()
But I was expecting something more useful like "In main ()"
EDIT: here is the build log, if it helps
-------------- Build: Debug in tests (compiler: GNU GCC Compiler)---------------
g++.exe -Wall -fexceptions -g -O -pedantic -Wextra -std=c++0x -std=c++14 -c D:\C\tests\main.cpp -o obj\Debug\main.o
D:\C\tests\main.cpp: In function 'int main()':
D:\C\tests\main.cpp:8:14: warning: 'plop' is used uninitialized in this function [-Wuninitialized]
cout << *plop << endl;
^
g++.exe -o bin\tests.exe obj\Debug\main.o -s
Output file is bin\tests.exe with size 542.00 KB
2nd EDIT: finally solved :)
For those who came here by google : strip symbols -s and Optimizer -O compiler options were checked in my case, theses options conflicts with -g as they removes debug symbols in compiled code.
Thanks for everyone for answering
you must initialize the int *plop; pointer like bellow, then print the value :
#include <iostream>
using namespace std;
int main()
{
int *plop = new int(15);
// *plop = 120; // you can change the plop value as custom
cout << *plop << endl;
return 0;
}
result will be : 15
You are dereferencing an uninitialized pointer. That's undefined behaviour and your program is meaningless.
The compiler is free to generate whatever it pleases (including code causing a segfault or not doing anything at all) - basically, all bets are off and you can trust nothing and you can't even count on your debugger showing you anything sane since it just has to work with what the compiler generated - which could be whatever.
Don't work with uninitialized variables / invoke UB.
I've read multiple posts here relating to dynamic libraries on os x and debugging with gdb. But I still can't figure out why I can't debug a simple test case.
The main issue is that when I start up GDB it never loads any shared libraries.
Update: I've tried this with GDB from macports, from homebrew, and built from source and the behavior is the same.
I have a class that I compile into a library.
Test.hpp
class Test {
public:
void set(int i);
void out() const;
private:
int i;
};
Test.cpp
#include "Test.hpp"
#include <iostream>
void Test::set(int ii) { i = ii; }
void Test::out() const {
auto j = i * 100;
std::cout << i << ", " << j << "\n";
++j;
std::cout << i << ", " << j << "\n";
}
I compile it and create a library with g++. Note: the behavior is the same with macports gcc and the gcc from xcode.
/opt/local/bin/g++-mp-4.8 -O0 -g -ggdb -Wall -c -std=c++11 -o Test.o Test.cpp
/opt/local/bin/g++-mp-4.8 -dynamiclib -o libTest.dylib Test.o
Then I test it with this simple main
#include "Test.hpp"
int main() {
Test t;
auto x = 4;
t.set(x);
t.out();
return 0;
}
This is compiled and linked with
/opt/local/bin/g++-mp-4.8 -O0 -g -ggdb -Wall -c -std=c++11 -o main.o main.cpp
/opt/local/bin/g++-mp-4.8 -L . -o testing main.o -lTest
Everything compiles and runs as expected. But when I try to debug this with gdb (installed from macports, or installed from source, the behavior is the same), I have problems.
As I step through main, if I call info sharedlibrary it always says "No shared libraries loaded at this time.", so it apparently never loads libTest.dylib. Therefore, I can't step into any of the Test member functions or create breakpoints anywhere in libTest.dylib.
Indeed ggdb installed from macports for some reason does not respect the DYLD_LIBRARY_PATH. However, if you "patch" your executable with the correct paths for the .dylibs you should be able to debug with ggdb. Take a look at this question and especially the answer by Akos Cz.
I'm having trouble getting the library working on macosx. First off, I tried to compile the following code, saved as rand.cpp, taken from the c++ website
#include <iostream>
#include <random>
int main()
{
const int nrolls=10000; // number of experiments
const int nstars=100; // maximum number of stars to distribute
std::default_random_engine generator;
std::normal_distribution<double> distribution(5.0,2.0);
int p[10]={};
for (int i=0; i<nrolls; ++i) {
double number = distribution(generator);
if ((number>=0.0)&&(number<10.0)) ++p[int(number)];
}
std::cout << "normal_distribution (5.0,2.0):" << std::endl;
for (int i=0; i<10; ++i) {
std::cout << i << "-" << (i+1) << ": ";
std::cout << std::string(p[i]*nstars/nrolls,'*') << std::endl;
}
return 0;
}
Upon running this with g++ rand.cpp -o rand i get the following errors
rand.cpp:9: error: ‘default_random_engine’ is not a member of ‘std’
rand.cpp:10: error: ‘normal_distribution’ is not a member of ‘std’
Searching around it seems to be suggested that the issue is the compiler, apparently thus library is only available to gcc11. I found a way to update gcc using the macport package as shown here Update GCC on OSX but I still don't know how to use this new compiler. Running g++ rand.cpp -o rand returns the same errors even when I change the compiler with sudo port select --set gcc gcc40 or sudo port select --set gcc mp-gcc46. I also tried using g++ -std=c++11 rand.cpp -o rand which just returns
cc1plus: error: unrecognized command line option "-std=c++11"
Does anyone know what I am doing wrong?
Try it with Clang++, which should be installed in your mac, or a new version of GCC.
gcc42: I had this version installed, it didn't work, and didn't recognize -std=c++0x and -std=c++11.
gcc49: Installed this with brew, it gave the same error but -std=c++11 made it work.
Clang++: Worked like a charm without even specifying the standard (it probably defaults to c++11).
Also, check if you have the latest version of the command line tools, if not, download them from the Downloads for Apple Developers website.
What you're doing wrong
The version you installed doesn't have the -std=c++11 option, but it should work with -std=c++0x or -std=gnu++0x, that's what it says in the manual for the 4.6 version.