This code fails to compile with an error that it can't resolve stio. Have I made some newbie mistake here?
Eclipse Version: 3.8.1 Mint KDE should all be up to date.
GCC Version: gcc (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int main() {
string numberGuessed;
int intNumberGuessed = 0;
int answer = 0;
answer = (rand() % 100) + 1;
do {
cout << "Guess a number "; // prints !!!Hello World!!!
getline(cin, numberGuessed);
intNumberGuessed = stoi(numberGuessed);
cout << "You guessed "<< numberGuessed << endl;
cout << "You are not correct. Try again" << endl;
} while (answer != intNumberGuessed);
cout << "you got it";
return 0;
}
The error message.
16:39:14 **** Incremental Build of configuration Debug for project Hello2 ****
make all
Building file: ../src/Hello2.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Hello2.d" -
MT"src/Hello2.d" -o "src/Hello2.o" "../src/Hello2.cpp"
../src/Hello2.cpp: In function ‘int main()’:
../src/Hello2.cpp:27:40: error: ‘stoi’ was not declared in this scope
intNumberGuessed = stoi(numberGuessed);
^
make: *** [src/Hello2.o] Error 1
src/subdir.mk:18: recipe for target 'src/Hello2.o' failed
16:39:14 Build Finished (took 613ms)
The std::stoi function is available since the c++11 standard.
Apparently your compiler version of GCC is too old, to take c++11 as the current default standard.
You may try to specify the -std=c++11 or -std=c++0x compiler flags, or update your gcc compiler to one of the most recent versions.
Here's a link explaining in detail how to set the compiler flags.
This might help you with updating your compiler version to the latest.
Related
I'm trying to diagnose a timing issue on a multi-core processor [Xeon Silver]. I think that the clocks have not been configured or synced between the processor. I'm using Eli Bendersky's [credited in the code snippet] threading examples to build a test instrument. I have made three changes. I made made the sleep occur first, and I added a call to std::chrono::system_clock::now() and tried to print it out. I'm building with gcc 4.8.5 on CentOS 7.5.
The code is as follows:
// // Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
#include <algorithm>
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <pthread.h>
int main(int argc, const char** argv) {
unsigned num_cpus = std::thread::hardware_concurrency();
std::cout << "Launching " << num_cpus << " threads\n";
// A mutex ensures orderly access to std::cout from multiple threads.
std::mutex iomutex;
std::vector<std::thread> threads(num_cpus);
for (unsigned i = 0; i < num_cpus; ++i)
{
threads[i] = std::thread([&iomutex, i]
{
// Simulate important work done by the tread by sleeping for a bit...
std::this_thread::sleep_for(std::chrono::milliseconds(200));
{
std::chrono::time_point ti = std::chrono::system_clock::now();
// Use a lexical scope and lock_guard to safely lock the mutex only for
// the duration of std::cout usage.
std::lock_guard<std::mutex> iolock(iomutex);
std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
}
});
}
for (auto& t : threads) {
t.join();
}
return 0;
}
I build with make:
CXX = g++
CXXFLAGS = -std=c++11 -Wall -O3 -g -DNDEBUG -pthread
LDFLAGS = -lpthread -pthread
clock-check: clock-check.cpp
$(CXX) $(CXXFLAGS) $^ -o $# $(LDFLAGS)
GCC gives me the following error:
[user#sbc1 concur]$ make clock-check
g++ -std=c++11 -Wall -O3 -g -DNDEBUG -pthread clock-check.cpp -o clock-check -lpthread -pthread
clock-check.cpp: In lambda function:
clock-check.cpp:32:67: error: ‘ti’ was not declared in this scope
std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
^
make: *** [clock-check] Error 1
ti is clearly in the same block scope as the print statement, and I'm baffled why the compiler is complaining. I have not found any restrictions on variables local to the lambda. Most of what I have found has been references to captures.
Your problem lies in this line:
std::chrono::time_point ti = std::chrono::system_clock::now();
std::chrono::time_point expect a type argument (e.g. std::chrono::time_point<std::chrono::system_clock>)
Prefer to use auto in this case:
auto ti = std::chrono::system_clock::now();
Then, you'll have an error since you try to output a std::chrono::duration in an output stream.
You should do:
std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch().count() << "\n";
It seems to be a bug in older gcc versions. With gcc 10.1 (--std=c++11) I get the error:
<source>: In lambda function:
<source>:23:34: error: missing template arguments before 'ti'
23 | std::chrono::time_point ti = std::chrono::system_clock::now();
| ^~
<source>:27:67: error: 'ti' was not declared in this scope; did you mean 'i'?
27 | std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
| ^~
|
The error about the missing template parameter (which is missing with gcc 4.5.8) on the declaration explains the second error.
Strangely gcc 4.8.5 with -std=c++11 happily compiles the code if you remove the line with std::cout: https://godbolt.org/z/6LREHF
Class template deduction is not available until c++17, so you need to specify your template parameters for chrono::timepoint. Alternatively, use auto:
auto ti = std::chrono::system_clock::now();
Furthermore, you attempt to stream a chrono::duration type, which is not possible. Use ti.time_since_epoch().count().
Live example
I have a C++ project based on CMake that uses Ninja. It's been build and ran using eclipse for C/C++. My current machine is a Mac OS.
The file:
#include <iostream>
#include <exception>
#include <string>
#include <stdexcept>
#include <vector>
#include <cmath>
using namespace std;
class Server {
private:
static int load;
public:
static int compute(long long A, long long B) {
load += 1;
if(A < 0) {
throw std::invalid_argument("A is negative");
}
vector<int> v(A, 0);
int real = -1, cmplx = sqrt(-1);
if(B == 0) throw 0;
real = (A/B)*real;
int ans = v.at(B);
return real + A - B*ans;
}
static int getLoad() {
return load;
}
};
int Server::load = 0;
int main() {
int T;
cin >> T;
while(T--) {
long long A, B;
cin >> A >> B;
/* Enter your code here. */
try{
cout << Server::compute(A, B) << endl;
} catch(invalid_argument e){
cout << "Exception: A is negative" << endl;
} catch(bad_alloc &e){
cout << "Not enough memory" << endl;
} catch(exception &e){
cout << "Exception: ";
cout << e.what() << endl;
} catch(...){
cout << "Other Exception" << endl;
}
}
cout << Server::getLoad() << endl;
return 0;
}
Build info:
cmake --build . -- -v
[1/2] /Library/Developer/CommandLineTools/usr/bin/c++ -O3 -DNDEBUG -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk -MD -MT CMakeFiles/deleteme.dir/deleteme.cpp.o -MF CMakeFiles/deleteme.dir/deleteme.cpp.o.d -o CMakeFiles/deleteme.dir/deleteme.cpp.o -c ../../deleteme.cpp
[2/2] : && /Library/Developer/CommandLineTools/usr/bin/c++ -O3 -DNDEBUG -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/deleteme.dir/deleteme.cpp.o -o deleteme && :
Build complete (0 errors, 0 warnings):
When I run:
Building in:
cmake --build . -- -v
ninja: no work to do.
Build complete (0 errors, 0 warnings):
It does not give me the chance to input the values. It just skips everything and finishes execution. If I put a cout right at the beginning, then the program works as expected.
Why is this happening?
Ps: The project complete path was removed from here for safety reasons. And yes, my project was created with the name 'deleteme'.
Pss: I took this snippet from HackerRank for studing purposes, so It should be fine. I've only added the try/catch and method call.
You are confusing building your program with running your program.
When you run the command cmake --build . -- -v, cmake will build your project. That means it will launch the appropriate tools to compile and link your program, which will produce an executable called deleteme somewhere in your build directory.
The subsequent invocation of the same command correctly reports that no work needs to be done (since you presumably haven't modified any of the source code between invocations).
To be clear, normally this will not run your program, which is why you don't get a prompt to input any values.
To run your program, which, if I understand correctly is what you are trying to do, simply run the executable deleteme that was produced by the build process. You will most likely find this executable in the build directory, that is, the directory where you ran the cmake --build . command. (Depending on your CMake project structure, you may also find it in a subdirectory of your build directory.)
I've figured It out how to solve this. I don't know what have caused It. It looks like ninja is not need if you have properly configured your environment variables, related to your compiler, inside Eclipse.
After doing that, everything works fine.
I am trying same,
http://www.linuxforums.org/forum/suse-linux/135465-gcov-g.html
Code from the link,
#include <iostream>
using namespace std;
void one(void);
void two(void);
void __gcov_flush(void);
int main(void)
{
int i;
while(true)
{
__gcov_flush();
cout << "Enter a number(1-2), 0 to exit " << endl;
cin >> i;
if ( i == 1 )
one();
else if ( i == 2 )
two();
else if ( i == 0 )
break;
else
continue;
}
return 0;
}
void one(void)
{ cout << "One is called" << endl; }
void two(void)
{ cout << "Two is called" << endl; }
but for me also it gives,
test.cpp:(.text+0x1d9): undefined reference to `__gcov_flush()'
collect2: ld returned 1 exit status
Tried the followings,
g++ -fprofile-arcs test.cpp
g++ -fprofile-arcs -g test.cpp
g++ -fprofile-arcs -ftest-coverage -g test.cpp
g++ -fprofile-arcs -ftest-coverage -g test.cpp -lgcov
I have also tried the "-lgcov" & "extern void __gcov_flush(void)" as mentioned in link above. I am currently on Ubuntu12.04 and g++ 4.6
So, I want to know if there is solution for this or gcov_flush doesnt work anymore.
void __gcov_flush();
Since the code is compiled as C++, this declares the existence of a C++ function of that name. C++ functions are subject to name mangling, so the (C++) symbol is not found in the (C) link library, and the linker (rightfully) complains about it.
If you declare the function, declare it as a function with C linkage:
extern "C" void __gcov_flush();
This should do the trick.
Note the commend by Paweł Bylica -- __gcov_flush() has been removed in GCC 11, you should use __gcov_dump().
I fixed this issue changing the settings.
Test Project --> Build Settings
Instrument Program Flow = Yes
I try my local compiler and online http://www.compileonline.com/compile_cpp11_online.php. Both generates the same errors.
#include <iostream>
#include <random>
using namespace std;
int main()
{
default_random_engine gen((random_device())());
cout << "Hello World" << endl;
return 0;
}
I have used g++ to compile the above code and the error is as follows:
error: expected primary-expression before ‘)’ token
g++ $1.cpp -o $1 -g -Wall -std=c++0x // error
However, I don't have such an issue with clang.
clang++ -o $1 -Werror $1.cpp -std=c++11 -O3 // fine
Question> can someone help me figure it out why? and how to correct it under g++ since I have to run g++ to debug my code.
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
clang version 3.4 (trunk 185180)
// Updated //
//http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);
for (int n=0; n<10; ++n)
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
I'm trying to compile my project in Eclipse.
However, it says that the main() is defined more than once. I grep'd my project dir and it found only one definition of main(), in main.cpp.
Apparently it is somewhere else.maybe a dir I linked to.
The only dirs I linked to are:
-ljson_linux-gcc-4.5.2_libmt
The compiler output is:
make all
Building file: ../src/main.cpp
Invoking: GCC C++ Compiler
g++ -Ijson_linux-gcc-4.5.2_libmt -I/usr/include/mysql -I/usr/include/jsoncpp-src-0.5.0/include -O0 -g3 -Wall -c -fmessage-length=0 -Ijson_linux-gcc-4.5.2_libmt -MMD -MP -MF"src/main.d" -MT"src/main.d" -o"src/main.o" "../src/main.cpp"
Finished building: ../src/main.cpp
Building target: Atms
Invoking: GCC C++ Linker
g++ -L-L/usr/include/jsoncpp-src-0.5.0/include/ -o"Atms" ./src/atmstypes.o ./src/base64.o ./src/hregex.o ./src/libparser.o ./src/log.o ./src/main.o ./src/serv.o ./src/sqlfeeder.o ./src/teleindex.o ./src/telepipe.o ./src/telesharedobject.o ./src/treet.o ./src/ttable.o -l-ljson_linux-gcc-4.5.2_libmt
./src/serv.o: In function `main':
/usr/include/c++/4.4/new:101: multiple definition of `main'
./src/main.o:/home/idan/workspaceCpp/Atms/Debug/../src/main.cpp:12: first defined here
/usr/bin/ld: cannot find -l-ljson_linux-gcc-4.5.2_libmt
collect2: ld returned 1 exit status
make: *** [Atms] Error 1
main.cpp:
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
#include <iostream>
#include <string.h>
#include <string>
#include "../h/hregex.h"
using namespace std;
string s = "this and7 that";
int main(int argc,char** argv){
cout << hregex::InitRegex() << endl;
cout << hregex::CheckHostnameField(s)<< "= this and7 that" << endl;
s = "this and7 that";
cout << hregex::CheckURLField(s)<< "= this and7 that" << endl;
s = "/lol/idan.html";
cout << hregex::CheckURLField(s)<< "= /lol/idan.html" << endl;
s = "/lol2#/idan.html";
cout << hregex::CheckURLField(s)<< "= /lol2#/idan.html" << endl;
return 0;
}
How can I prevent the error from appearing?
g++ says serv.o has a main function.
If there actually is no main() it serv.cpp, check the includes, maybe you did a bad #include and included a .cpp instead of a .h ?
As an extra remark :
it tries to bind against the library "-ljson_linux-gcc-4.5.2_libmt"
So there is "-l-ljson_linux-gcc-4.5.2_libmt" in the link command line. Remove the -l in your configuration