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.
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...
running on version 11.1.0 of gcc and g++. Every time I run this code I run into issues it says std::numbers was not declared. I tried running g++ randomCodeWhileReading.cpp -o main-std=c++20 within my terminal (im running ubuntu linux) and still no change. Here is the code in question:
#include <iostream>
#include <numbers>
int main()
{
const long double pi {0};
const long double pi2 {0};
pi = std::numbers::pi_v<long double>;
pi2 = std::numbers::pi_v<long double>;
std::cout << pi << std::endl << pi2;
}
Just wanted to see the numbers module in action nothing else. (is it even called a module or is it a header file?)
EDIT 10/6/21:
The modifying a constant variable has been fixed. However, this code still wont run on my computer. Namely, the #include <numbers> does not seem to work on my machine it throws an error even when using -std=c++20. I am running gcc and g++ version 11.1 See error below:
gcc ex2_03.cpp -o -std=c++20
ex2_03.cpp: In function ‘int main()’:
ex2_03.cpp:22:65: error: ‘std::numbers’ has not been declared
22 | const double pond_diameter {2.0 * std::sqrt(pond_area/ std::numbers::pi)}; //find diameter by finding radius & multiplying by 2
|
however I was unable to replicate using godbolt.org (similar program not the same but uses as well). Clearly, it seems that this is an issue with my machine. How would I go about fixing this?
EDIT 10/8/21:
I ran the code again using more flags and changing -std=c++20 to -std=c++2a this was what was returned:
chris#chris-Aspire-E5-576G:~/Desktop/programming/c++/Learning$ ls
ex2_02 HelloWorld randomCodeWhileReading textbookExample1
ex2_02.cpp HelloWorld.cpp randomCodeWhileReading.cpp textbookExample1.cpp
ex2_02.o HelloWorld.o randomCodeWhileReading.o textbookExample1.o
ex2_03 main textbookDebug textbookOutputNameAndAge.cpp
ex2_03.cpp outputNameAndAge textbookDebug.cpp
ex2_03.o outputNameAndAge.o textbookDebug.o
chris#chris-Aspire-E5-576G:~/Desktop/programming/c++/Learning$ g++ -g -Wall -pedantic -std=c++2a -o randomCodeWhileReading.cpp
g++: fatal error: no input files
compilation terminated.
added the ls output to show I was in the correct directory.
EDIT 10/8/21 v2:
I used the following command and did not receive an error.
g++ randomCodeWhileReading.cpp -o main -std=c++20
Now just confused where the output went. By #nate's responses I assume it was sent to main? Just wanted to see a cout using std::numbers::pi
EDIT 10/8/21 v3:
All clear nate explained program can be ran by using ./main
EDIT 10/8/21 v4:
... I repeated the earlier command and got a error:
g++ randomCodeWhileReading.cpp -o main -std=c++20
cc1plus: fatal error: randomCodeWhileReading.cpp: No such file or directory
compilation terminated.
can someone explain what went wrong this time? (I am still in the same directory). After using ls it seems that the file is no longer in the directory seems to be deleted?
EDIT 10/8/21 v5:
I think the file got deleted when I was explaining the error to a friend and the wrong ways I was running the command lol. All good :D !
You need to compile with the extra flag -std=c++20.
Moreover, there is an error in your code: pi and pi2 are declared const, hence you cannot modify them after they are initialized. Use this instead:
#include <iostream>
#include <numbers>
int main()
{
const long double pi = std::numbers::pi_v<long double>;
const long double pi2 = std::numbers::pi_v<long double>;
std::cout << pi << std::endl << pi2;
}
Please try this code and this "compile" command on your machine with your version of g++:
/*
* TEST ENVIRONMENT: MSYS2 (Windows 10)
* COMPILER:
* g++ --version
* g++.exe (Rev5, Built by MSYS2 project) 10.3.0
* BUILD COMMAND:
* g++ -g -Wall -pedantic -std=c++2a -o x x.cpp
* <= NOTE: the correct command for C++ 20 compatibility in g++ 10.x is "-std=c++2a"
* RUN COMMAND:
* ./x
* 2pi=6.28319
*/
#include <iostream>
#include <numbers>
int main()
{
auto two_pi = 2*std::numbers::pi;
std::cout << "2pi=" << two_pi << '\n';
}
If it works, great. If it's the same, try "-std=c++20" and/or "-std=gnu++20". Look here for details: https://gcc.gnu.org/projects/cxx-status.html
See also:
https://stackoverflow.com/a/67453352/421195
https://stackoverflow.com/a/67406788/421195
Definitely "Update" your post to report back what happens. Be sure to copy/paste your commands and any error messages EXACTLY.
'Hope that helps.
I am writing a personal project in c++ which needs to access to files in some directories, hence I decided to use the filesystem library. I encountered some problems when I try to compile my project on MacOS and on Linux.
The code snippet is the following
#include <iostream>
#include <fstream>
int main(){
std::string path = "Inner";
std::cout << "Files in " << path << " directory :" << std::endl;
for (const auto & entry : std::filesystem::directory_iterator(path))
std::cout << entry.path() << std::endl;
return 0;
}
When I compile it on my MacBook Pro (clang version 11.0.3 (clang-1103.0.32.62)) with
g++ -o test test.cpp -std=c++17 -Wall
everything works fine. But as soon as I move to Linux (Ubuntu 19.04, g++ 8.3.0) I get the following error:
test.cpp: In function ‘int main()’:
test.cpp:8:33: error: ‘std::filesystem’ has not been declared
for (const auto & entry : std::filesystem::directory_iterator(path)){
I include then the filesystem library with #include <filesystem>:
#include <iostream>
#include <fstream>
#include <filesystem>
int main(){
std::string path = "Inner";
std::cout << "Files in " << path << " directory :" << std::endl;
for (const auto & entry : std::filesystem::directory_iterator(path))
std::cout << entry.path() << std::endl;
return 0;
}
compile it via g++ -o test test.cpp -std=c++17 -Wall -lstdc++fs and everything works fine on Linux too (note that I had to add -lstdc++fs).
Why is there this different behaviour on MacOS and on Linux? Does it depends on the compiler? What happens with Windows OS (I do not have any Windows PC at home)?
I found a related question and its answer here, but it does not seem to explain why in the first case (with clang) everything works fine also without including filesystem library.
Using 'g++' is not using clang you should use 'clang++'
Gcc should not be platform dependent but it might be different version
At any case, you should explicitly include header files needed, and std::filesystem is defined in "<filesystem>"
regarding the need to add "lstdc++fs' - this is a hint that actually g++ version is different and uses different llvm versions. As described in https://en.cppreference.com/w/cpp/filesystem
Notes:
Using this library may require additional compiler/linker options. GNU implementation prior to 9.1 requires linking with -lstdc++fs and LLVM implementation prior to LLVM 9.0 requires linking with -lc++fs
I'm trying to build a write of software with the Tensor module provided as unsupported from eigen3. I've written a simple piece of code that will build with a simple application of VectorXd (just printing it to stdout), and will also build with an analogous application of Tensor in place of the VectorXd, but WILL NOT build when I do not throw an optimization flag (-On). Note that my build is from within a conda enviromnent that is using conda-forge compilers, so the g++ in what follows is the g++ obtained from conda forge for ubuntu. It says its name in the error messages following, if that is perceived to be the issue.
I have a feeling this is not about the program I'm trying to write, but just in case I've included an mwe.cpp that seems to produce the error. The code follows:
#include <eigen3/Eigen/Dense>
#include <eigen3/unsupported/Eigen/CXX11/Tensor>
#include <iostream>
using namespace Eigen;
using namespace std;
int main(int argc, char const *argv[])
{
VectorXd v(6);
v << 1, 2, 3, 4, 5, 6;
cout << v.cwiseSqrt() << "\n";
Tensor<double, 1> t(6);
for (auto i=0; i<v.size(); i++){
t(i) = v(i);
}
cout << "\n";
for (auto i=0; i<t.size(); i++){
cout << t(i) << " ";
}
cout << "\n";
return 0;
}
If the above code is compiled without any optimizations, like:
g++ -I ~/miniconda3/envs/myenv/include/ mwe.cpp -o mwe
I get the following compiler error:
/home/myname/miniconda3/envs/myenv/bin/../lib/gcc/x86_64-conda_cos6-linux-gnu/7.3.0/../../../../x86_64-conda_cos6-linux-gnu/bin/ld: /tmp/cc2q8gj4.o: in function `Eigen::internal::(anonymous namespace)::get_random_seed()':
mwe.cpp:(.text+0x15): undefined reference to `clock_gettime'
collect2: error: ld returned 1 exit status
If instead I ask for 'n' optimization level, like the following:
g++ -I ~/miniconda3/envs/loos/include/ -On mwe.cpp -o mwe
The program builds without complaint and I get expected output:
$ ./mwe
1
1.41421
1.73205
2
2.23607
2.44949
1 2 3 4 5 6
I have no clue why this little program, or the real program I'm trying to write, would be trying to get a random seed for anything. Any advice would be appreciated. The reason why I would like to build without optimization is so that debugging is easier. I actually thought all this was being caused by debug flags, but I realized that my build tool's debug setting didn't ask for optimization and narrowed that down to the apparent cause. If I throw -g -O1 I do not see the error.
Obviously, if one were to comment out all the code that has to do with the Tensor module, that is everthing in main above 'return' and below the cwiseSqrt() line, and also the include statement, the code builds and produces expected output.
Technically, this is a linker error (g++ calls the compiler as well as the linker, depending on the command line arguments). And you get linker-errors if an externally defined function is called from somewhere, even if the code is never reached.
When compiling with optimizations enabled, g++ will optimize away uncalled functions (outside the global namespace), thus you get no linker errors. You may want to try -Og instead of -O1 for better debugging experience.
The following code should produce similar behavior:
int foo(); // externally defined
namespace { // anonymous namespace
// defined inside this module, but never called
int bar() {
return foo();
}
}
int main() {
// if you un-comment this line, the
// optimized version will fail as well:
// ::bar();
}
According to man clock_gettime you need to link with -lrt if your glibc version is older than 2.17 -- maybe that is the case for your setup:
g++ -I ~/miniconda3/envs/myenv/include/ mwe.cpp -o mwe -lrt
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.