I'm starting a project using C++, which I haven't used before outside of a handful of school projects - nowhere near the scope of what I'm tackling now.
My goal is to try my best to follow the C++ Core Guidelines as I work to avoid errors, improve performance, and most importantly: improve maintainability of my code.
I've been running into literally hundreds of issues ranging from my g++ / Clang++ versions not being right to standard libraries not being found to g++ using the wrong version of C++ for compilation to very basic functions not behaving as expected - and I haven't even started to look into autotools, so I expect many more headaches to follow.
This question is specific to one part of the C++ Core Guidelines, though. Interfaces 6: Prefer Expects() for expressing preconditions
I tried writing the following simple code:
#include <iostream>
using namespace std;
int square(int x) {
Expects(x > 0);
return x * x;
}
int main() {
cout << square(3) << endl;
return 0;
}
This threw an error in g++:
$> g++ -std=c++17 main.cpp
main.cpp: In function ‘int square(int)’:
main.cpp:7:2: error: ‘Expects’ was not declared in this scope
Expects(x > 0);
^~~~~~~
-> [1]
I tried using Clang, as well, but it has an entirely different (and unrelated) problem:
$> clang++ -x c++ main.cpp
main.cpp:1:10: fatal error: 'iostream' file not found
#include <iostream>
^~~~~~~~~~
1 error generated.
-> [1]
I haven't figured out how to fix that one yet, so I'm not bothering with it.
Expects is part of the GSL library. You have to use some GSL library implementation, which you can find on Github:
https://github.com/martinmoene/gsl-lite
https://github.com/Microsoft/GSL
These are the ones I have off the top of my head.
The CPP Guidelines likely allude to the "contracts" proposal which provides the same checks via attributes. It was scheduled for C++20, but later removed for lack of consensus on its scope. See p1823r0 and a standard committee member's Reddit thread on the rationale leading to the removal.
Apart from GSL, Excepts exists also in C++20 not in C++17 with a little different syntax
https://en.cppreference.com/w/cpp/language/attributes/contract
Related
I am running the below program on Dev-C++, and I am not able to execute it, as it always give me error while compiling the program.
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v2{2,3,4,5};
for(int x : v2)
{
cout<<x<<" ";
}
return 0;
}
[Warning] extended initializer lists only available with -std=c++11 or
-std=gnu++11
It always give me error, I just wanted to confirm, whether this type of Vector Initialisation is right? Or I am doing it the wrong way?
I am new to the community, sorry If this has been answered previously also, you could redirect me to the previous answer also.
Avoid use of <bits/stdc++.h>. It is not supported by some compilers and IDEs, plus it includes the entire STL library, which is unnecessary.
Instead, use specific templates such as <vector> in your case, since your using an std::vector. Don't forget to include <iostream> for std::cout as well.
[Warning] extended initializer lists only available with -std=c++11 or -std=gnu++11
Provided your compiler supports C++ uptil a specific standard, you can set the standard using -std=standard, where 'standard' can be c++11, c++14, c++17 or c++20, taking into account of the recent versions of the C++ standard.
Your compiler clearly supports c++11 (in fact every compiler nowadays does, thats like the minimum) so just include that while compiling:
g++ -std=c++11 Filename.cpp -o Filename
This will compile your C++ file using g++ compiler with C++11 standard, and create an object file of the source file 'Filename.cpp'.
Here is my code:
#include <iostream>
#include <iomanip>
#include <complex>
#include <cmath>
int main()
{
using namespace std::complex_literals;
std::cout<< std::fixed<<std::setprecision(1);
std::complex<double> z1= 1i *1i; //imaginary unit squared
std::cout<<"i * i= " <<z1 <<'\n';
std::complex<double> z2=std::pow(1i, 2); //imaginary unit squared
std::cout <<"pow(i,2) =" <<z2 <<'\n';
}
I compile with gcc hello.cpp -lstdc++ -o hello.o
Basically it won't let me double the powers of a complex number when i do std::complex z2=std::pow(1i, 2);..
I get the following error
error: no matching function for call to 'pow(complex int, int)'
std::complex z2=std::pow(1i, 2);
However, if i remove the complex number and do std::complex z2=std::pow(2, 2);
it returns 4, the correct answer..
There are many more lines of compile errors, but i made it brief
This answer follows up the comments to the original question:
you have to force the compiler to use the c++14 standard with the -std=c++14 option because the literal operator""i is part of the C++14 spec.
GCC uses c++14 by default since version 6.1. Check your compiler version with gcc -v and refer to this link for GCC standard support.
EDIT:
I was able to reproduce the compiling issue with GCC 6.3 through the link provided by Mr Richard Critten in the comments to the original question, who was the first to point to the correct answer. My apology because I totally overlooked the reference to the C++14 standard.
Anyway, for the sake of clarity, I'm editing this answer, because I've found something that may be interesting to share.
The reason why compiling with GCC 6.3 fails is the fact that the reference standard has been changed in December 2016 from C++14 to GNU++14, see here.
GNU++14 is an extension to the C++ standard, that, among other things, provides additional functions overload for standard APIs.
I've found that with GNU++14 SFINAE fails in finding a proper overload for the std::pow() functions unless the type is explicitly set in the template call like in the snipped below:
std::complex<double> z2=std::pow<double>(1i, 2);
The GNU++14 includes changes to the cmath and complex header files, that I believe are the cause of the issue.
Turning on the C++14 flag, that is not the default anymore, fixes the problem.
I don't know why it is not compiling on your system, it runs fine on mine.
I think something is wrong with your compiler. And, not the version. yet you could try std::cout << __cplusplus. See what this prints.
C++11 doesn't recognize std::complex_literals, so doubt that is the case, but yet the compiler still couldn't find the function.
I honestly don't understand why it is searching for (complex int, int). The compiler is either corrupt or an old beta version.
You should either download a fresh version of the compiler or run it online somewhere. Try adding -std=c++14, but I doubt that would help.
Try your code here(it works):
https://www.jdoodle.com/online-compiler-c++14
So, I installed Microsoft Visual Studio.. I am using the clang compiler and my program ran smoothly with no errors!
Thanks for all the help guys, but i think clang is a better c++ compiler
I'm going to keep it fast and simple.
Here's the code I've written:
#include <iostream>
#include <thread>
void myFunc()
{
std::cout << "Hello!" << std::endl;
}
int main()
{
std::thread myThread(myFunc);
myThread.join();
return 0;
}
This is the command I've used to compile the program:
g++ threads.cc -o threads.exe -std=c++11
This is the error I'm getting:
threads.cc: In function 'int main()':
threads.cc:11:6: error: 'thread' is not a member of 'std'
std::thread myThread(myFunc);
^
threads.cc:13:6: error: 'myThread' was not declared in this scope
myThread.join();
^
I'm running Windows 10 and as you can see I'm trying to compile the program with GCC.
Can anyone help me with this? I've tried a few different ways to do multi-threading in C++, but none have worked.
The day after tomorrow I'll attend to a programming competition at my school and to make things go faster (the programs may only take up to 5 seconds to process data, which can be a lot) I'm thinking multi-threading could really help. You might think I should know this if I learn programming at school, but I haven't started that course yet and I'm just interested in the competition because it seems fun.
EDIT:
I have now installed the packages "mingw32-libpthreadgc" and "mingw32-libpthreadgce" (both the dev and dll classes). I also installed the "mingw32-pthreads-w32" (dev, doc and lic classes).
I have tried a few different includes <thread>, <pthread>, <pthread.h>. I have also tried adding the flag "-pthread" and "-lpthread". Also, I don't think we'll be allowed to use those flags anyways.
Nothing has worked so far.
I would be awesome if anyone could give a concrete example of which package / packages must be installed, which file / files to include and a short example code (in case mine won't work). We're not allowed to use any libraries except for the standard ones, but running a linux vm is probably fine, so any linux-only example works too.
I haven't found an example like that anywhere yet, so that would be awesome! Thanks!
(Yes, I did restart my computer)
When you install mingw sepect posix threads instead of default
So in my CSE course we are given a header file to use right now for our programs that we're writing.
Unfortunately I can't get terminal to compile using that header, it gives quite a few errors (compiling with just 'g++'). Also, when I'm at my university and I'm using PuTTY I get the same errors while using this header. However, I don't get the errors when I compile with 'g++ -std=c++14'.
I've tried compiling with this command on terminal on my mac, but it says it doesn't recognize the c++14 part.
dhcp-10-202-147-243:hw1pr1 Admin$ g++ -std=c++14 hw1pr1.cpp
error: invalid value 'c++14' in '-std=c++14'
Any help on how I could get this to work would be greatly appreciated. Hopefully this all made some sort of sense.
Here's the error I get when I compile with the header file I'm talking about in terminal with just g++.
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/ext/hash_map:212:5: warning:
Use of the header <ext/hash_map> is deprecated. Migrate to <unordered_map>
[-W#warnings]
# warning Use of the header <ext/hash_map> is deprecated. Migrate to ...
^
In file included from read_first_name.cpp:1:
./std_lib_facilities_4.h:43:20: error: no matching function for call to object
of type 'hash<char *>'
return hash<char*>()(s.c_str());
^~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/ext/__hash:39:12: note:
candidate function not viable: 1st argument ('const value_type *'
(aka 'const char *')) would lose const qualifier
size_t operator()(char *__c) const _NOEXCEPT
^
In file included from read_first_name.cpp:1:
./std_lib_facilities_4.h:112:8: warning: comparison of unsigned expression < 0
is always false [-Wtautological-compare]
if (i<0||size()<=i) throw Range_error(i);
~^~
./std_lib_facilities_4.h:118:8: warning: comparison of unsigned expression < 0
is always false [-Wtautological-compare]
if (i<0||size()<=i) throw Range_error(i);
~^~
3 warnings and 1 error generated.
This error doesn't happen and the program will compile fully when I use PuTTY and 'g++ std=c++14'
There's lots of change between C++ standards, so what is valid in one revision need not be in another.
g++ defaults to -std=gnu++98 for C++, which is the decades old C++98-standard enhanced with GNU extensions (most of which are conformant).
Choose the proper revision: -std=c++1y -pedantic is a very close approximation to C++14.
What changes introduced in C++14 can potentially break a program written in C++11?
Looking at what you say you're having to use and the name format of that .cpp file, I think I'm in the same class. A year later, looks like, but here's my solution for archive's sake:
The std_lib_facilities.h header comes with the Bjarne Stroustrup textbook, "Programming: Principles and Practices Using C++". For those unaware, Bjarne Stroustrup invented C++ (he has a pretty good idea what he's talking about). Incidentally, the book is a fantastic way to learn C++, if one takes the time to actually read it. The std_lib_facilities.h header is just a convenient header file for beginners in C++, containing links to all the major standard libraries used in the textbook, as well as some helper functions that help account for potential mistakes or errors, or are just convenient for learning (such as an error() function that handles simple exception throwing for the student, or adding an "out of bounds" check for vectors). It's ultimately just a way to allow students to hop right into code without having to learn specifics about the header.
Stroustrup keeps updated with C++ and thus includes several libraries that require the c++11 standard. The CSCE department wants its students (at least in this early class) to connect to the department's Unix system and compile from there, in order to avoid confusion with downloading and updating compilers.
I happened to already have had a couple C++ classes beforehand, and thus already had g++ set up on my Ubuntu laptop. I avoided including the std_lib_facilities for as long as possible since I was getting the same error as Topic Creator Joe, where g++ didn't recognize the "c++11" part (manually including the required libraries worked fine until we had to use a class from the textbook that used one of the header's helper functions) . Eventually, I found a help topic online that advised me simply to update my g++ compiler to 4.7 or higher, since 4.6 and lower doesn't have support for C++11 (or, of course, C++14). It was oddly rather involved compared to updates one might be used to on Mac or Windows, and I doubt the exact process would apply, but that is (was?) likely the problem: it's just an older version of g++, and it needs an update to compile C++11 and later. I recommend searching for ways to update g++/gcc for Mac.
Should, y'know, anyone else with this problem stumble upon this and not have their problem solved yet.
I created a simple program to learn how to use threading. This is the code i created
#include <iostream>
#include <stdlib.h>
#include <thread>
using namespace std;
void count_asc();
void count_desc();
int main() {
thread first(count_asc);
thread second(count_desc);
first.join();
second.join();
system("pause");
return 0;
}
void count_asc(){
int ctr;
for(ctr=1;ctr<=10;ctr++){
cout<<"First thread: "<<ctr<<endl;
}
}
void count_desc(){
int ctr;
for(ctr=10;ctr>=1;ctr--){
cout<<"Second thread: "<<ctr<<endl;
}
}
I am using Dev C++ 5.5.3. I have read other questions about this but me being a beginner in programming cannot really understand advanced instructions. When this code is compiled the following error is produced
main.cpp: In function 'int main()':
main.cpp:11:2: error: 'thread' was not declared in this scope
main.cpp:11:9: error: expected ';' before 'first'
main.cpp:12:9: error: expected ';' before 'second'
main.cpp:14:2: error: 'first' was not declared in this scope
main.cpp:15:2: error: 'second' was not declared in this scope
I have already included -std=c++11 in the c++ compiler additional command-line options in the project option of the Dev C++ but i can't still remove the errors. Can you please check what i am doing wrong? also as much as possible i dont want to start using other libraries as i am having a hard time building them(ex. boost)
The problem is most likely due to lack of support for C++11's std::thread in the build of GCC 4.7.1 included with TDM-GCC. Have a look at this question, for details. Your code compiles fine with GCC 4.8.1 (although it still has runtime errors):
http://ideone.com/oUhvi3
I would therefore suggest that to resolve your problem, you try updating to a more recent version of the compiler. According to this link and this link doing so should be a simple matter of installing the most recent version of the compiler into the folder where it currently resides, or alternatively, installing it in a new folder and updating the settings in Dev C++ to point to the new compiler.
However, since you are new to C++ (and programming in general), and therefore have no particular attachment to Dev C++, I would recommend that you instead switch to a more modern and widely used IDE. MS Visual Studio is a good bet for Windows, but there are plenty of open source and cross platform IDEs available for C++. Using an IDE which is popular is recommended for beginners, as you are much more likely to find sources of help and support online, and more likely to get answers on sites such as Stackoverflow, when you get stuck. There are tons of Stackoverflow questions relating to IDEs. Examples (from a quick Google search):
What is the good cross platform C++ IDE?
Best C++ IDE or Editor for Windows
https://stackoverflow.com/questions/535369/what-is-the-best-free-windows-c-ide-compiler