I am using VS Code to code C++. It performs totally fine. But whenever I use auto keyword in my code, the program simply fails to Compile.
For example, to iterate over a string my code without using auto keyword will look like
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s("Hello");
for(int i=0;i<s.length();i++)
{
cout<<s.at(i)<<' ';
}
cin.get();
}
It compiles find and runs giving Correct Output.
Executing task: g++ -g -o helloworld helloworld.cpp
Terminal will be reused by tasks, press any key to close it.
OUTPUT : H e l l o
But whenever I try to perform the same job but using auto keyword, the code looks like
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s("Hello");
for(auto c:s)
{
cout<<c<<' ';
}
cin.get();
}
But it gives Compile Time Error
Executing task: g++ -g -o helloworld helloworld.cpp
helloworld.cpp: In function 'int main()':
helloworld.cpp:7:14: error: 'c' does not name a type
for(auto c:s)
^
helloworld.cpp:11:5: error: expected ';' before 'cin'
cin.get();
^
helloworld.cpp:12:1: error: expected primary-expression before '}' token
}
^
helloworld.cpp:12:1: error: expected ')' before '}' token
helloworld.cpp:12:1: error: expected primary-expression before '}' token
The terminal process terminated with exit code: 1
Terminal will be reused by tasks, press any key to close it.
Please help me out.
This is the clue:
Executing task: g++ -g -o helloworld helloworld.cpp
I suspect you need to compile with -std=c++11 or later.
Older builds of gcc/g++ will default to C++ 98 standard before the auto keyword was introduced. There might be other configurations where this is the default as well. The workaround is simple.
Configure your build such that the task being compiled is this:
g++ -std=c++11 -g -o helloworld helloworld.cpp
You can also use -std=c++14 or -std=c++17 if available.
Related
I am trying to compile this code with MinGW g++ (i686-win32-dwarf-rev0, Built by MinGW-W64 project) 8.1.0
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<int, int> mmap;
mmap[0]=10;
mmap[1]=20;
mmap[2]=30;
mmap[3]=40;
mmap[4]=50;
for(auto [x,y]:mmap){
cout<<x<<"->"<<y<<endl;
}
return 0;
}
Compiling with c++11 flag gives this
E:\Code>g++ temp.cpp -std=c++11
temp.cpp: In function 'int main()':
temp.cpp:89:14: warning: structured bindings only available with -std=c++17 or -std=gnu++17
for(auto [x,y]:mmap){
and compiling with c++17 flag gives lines and lines of errors.
g++ temp.cpp -std=c++17
OK, so I figured this out and this came out to be the very first line
#include <bits/stdc++.h>
Including iostream and map instead of the above line results in a clean compilation.
#include<iostream>
#include<map>
Now I have one more reason as to Why should I not #include <bits/stdc++.h>?
I have a basic C++ file like so:
#include <iostream>
using namespace std;
int main() {
float x = rand();
cout << x << endl;
return 0;
}
When I run this through g++ on Ubuntu with g++ test.cpp -o test -std=c++11, I get no errors, and the program runs just fine. But when I run it through g++ on MinGW with the same command, I get the following error:
test.cpp: In function 'int main()':
test.cpp:6:17: error: 'rand' was not declared in this scope
float x = rand();
^
I have GCC version 5.3.0. Attempting to compile with g++ test.cpp -o test.exe -std=gnu++11 or g++ test.cpp -o test.exe -std=c++0x yield the same result.
You must include library for the random function first
i-e
#include < cstdlib >
After that your code will work perfectly
Here is the correct code
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
float x = rand();
cout << x << endl;
return 0;
}
Some compilers allow you to use random function without including library but standard C++ compilers doesn't allow you.
Hope this will help you
I am trying to program with xerces-c on windows.
I have successfully built the library and compiled a simple program with success, barebone, with just cmd and notepad. However when I tried to move things to eclipse, things got a bit out of hand.
By simply having a c++ helloworld sample, then including the include files into the project path and build, eclipse is refusing to build the project, generating a lot of error, which I think mostly related to the namespace.
The errors goes as follow:
Info: Internal Builder is used for build
g++ -I...blablabla -O3 -Wall -c -fmessage-length=0 -o "src\\helloworld.o" "..\\src\\helloworld.cpp"
gcc -O3 -Wall -c -fmessage-length=0 -o "src\\includes\\xercesc\\util\\RefStackOf.o" "..\\src\\includes\\xercesc\\util\\RefStackOf.c"
..\src\includes\xercesc\util\RefStackOf.c:30:1: error: unknown type name 'XERCES_CPP_NAMESPACE_BEGIN'
XERCES_CPP_NAMESPACE_BEGIN
..\src\includes\xercesc\util\RefStackOf.c:35:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
template <class TElem>
^
..\src\includes\xercesc\util\RefStackOf.c:44:10: error: expected '=', ',', ';', 'asm' or '__attribute__' before '<' token
template <class TElem> RefStackOf<TElem>::~RefStackOf()
..\src\includes\xercesc\util\RefStackOf.c:...
...this and that, this and that.... and finally...
..\src\includes\xercesc\util\RefStackOf.c:160:1: error: expected '=', ',', ';', 'asm' or '__attribute__' at end of input
XERCES_CPP_NAMESPACE_END
and if I removed the file in error, error will just pop up to another file with the same format, beginning with "I dunno what XERCES_CPP_NAMESPACE_BEGIN means"
I have also tried using another builder, say mingw32-make, but it also generates error in the same format. Only changing the title a bit, and perhaps the files are compiled in different order, starting with this:
mingw32-make all
'Building file: ../src/includes/xercesc/util/BaseRefVectorOf.c'
'Invoking: GCC C Compiler'
gcc -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/includes/xercesc/util/BaseRefVectorOf.d" -MT"src/includes/xercesc/util/BaseRefVectorOf.o" -o "src/includes/xercesc/util/BaseRefVectorOf.o" "../src/includes/xercesc/util/BaseRefVectorOf.c"
../src/includes/xercesc/util/BaseRefVectorOf.c:24:1: error: unknown type name 'XERCES_CPP_NAMESPACE_BEGIN'
XERCES_CPP_NAMESPACE_BEGIN
I am guessing that the build program does not understand how to replace the
XERCES_CPP_NAMESPACE_BEGIN, with
namespace XERCES_CPP_NAMESPACE { }
namespace xercesc = XERCES_CPP_NAMESPACE;
But I don't know of a way to teach the builder how to do this, nor I am sure if I have compiled the library in the correct way.
Can someone point me in some direction as to how to solve this? I can compile a simple program by just using cmd, so certainly I should be able to do it in Eclipse.
background:
OS: Windows 8 64bit
compiler: mingw-w64 5.3.0 posix-seh-rev0
lib compiled with msys
lib compilation command:
./configure --prefix=/specific-location --host=x86_64-w64-mingw32 --enable-netaccessor-winsock --enable-transcoder-windows --disable-pretty-make
make LDFLAGS=-no-undefined
make check
make install
cmd compilation command: g++ -Llib -Iinclude -o b.exe test.cpp
so you can see that I have also included every xerces-c header into the compiler with the -Iinclude command, so I reckon that g++ should not produce error when invoked in Eclipse, not that I know anything if its gcc.
simple program that ran when simply compiled with cmd:
//test.cpp
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/sax/HandlerBase.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <iostream>
using namespace std;
using namespace xercesc;
int main (int argc, char* args[]) {
try {
XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch) {
char* message = XMLString::transcode(toCatch.getMessage());
cout << "Error during initialization! :\n"
<< message << "\n";
XMLString::release(&message);
return 1;
}
XercesDOMParser* parser = new XercesDOMParser();
parser->setValidationScheme(XercesDOMParser::Val_Always);
parser->setDoNamespaces(true); // optional
ErrorHandler* errHandler = (ErrorHandler*) new HandlerBase();
parser->setErrorHandler(errHandler);
char* xmlFile = "x1.xml";
try {
parser->parse(xmlFile);
DOMDocument* xmlDoc = parser->getDocument();
DOMElement* elementRoot = xmlDoc->getDocumentElement();
if( !elementRoot ) throw(std::runtime_error( "empty XML document" ));
DOMNodeList* children = elementRoot->getChildNodes();
const XMLSize_t nodeCount = children->getLength();
cout << nodeCount << " nodes\n";
}
catch (const XMLException& toCatch) {
char* message = XMLString::transcode(toCatch.getMessage());
cout << "Exception message is: \n"
<< message << "\n";
XMLString::release(&message);
return -1;
}
catch (...) {
cout << "Unexpected Exception \n" ;
return -1;
}
delete parser;
delete errHandler;
return 0;
}
#EDIT
After further investigation, it seems that the XERCES_CPP_NAMESPACE_BEGIN is handled in preprocessor, but its only defined in the file util/XercesDefs.hpp
In the files with compilation error, they always begin with
#if defined(XERCES_TMPLSINC)
#include <xercesc/util/RefStackOf.hpp> //or include anything else blablabla, which ultimately leads to XercesDefs.hpp
#endif
I searched through the entire build directory for the string XERCES_TMPLSINC, it was contained in 44 .c or .hpp files, but everyone of them is #if !defined(XERCES_TMPLSINC) <===== WRONGWRONG , so like XERCES_TMPLSINC was never actually defined.
According to some forum post, XERCES_TMPLSINC was required for some old c compilers, so does anyone know how to fix this in my build? how could I define XERCES_TMPLSINC in the project? I have tried adding #define XERCES_TMPLSINC to the helloworld file but it still does not work.
#EDIT
my bad, actually all the .c files contained #if defined(XERCES_TMPLSINC) and all hpp files were #if !defined(XERCES_TMPLSINC), this definitely seems a c and c++ thing?
I was able to compile it in Ecliplse (on Linux) by adding the following preprocessor defs in g++:
-DXERCESC_INCLUDE_GUARD_WEAVEPATH_CPP -DXERCES_HAVE_STDINT_H -DXERCES_TMPLSINC.
On Windows I think you should substitute the with
-DXERCES_HAVE_STDINT_H -DXERCES_HAVE_CSTDINT
I am using geany (code::blocks wouldnt run my programs) as a compiler to compile a simple c++ program with one class. I am on Linux Mint 17 on a Dell Vostro 1500. Compiling works fine with both .cpp files, but the header file gives this error:
gcc -Wall "Morgan.h" (in directory: /home/luke/Documents/Coding/Intro#2)
Morgan.h:5:1: error: unknown type name ‘class’
class Morgan
^
Morgan.h:6:1: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token
{
^
Compilation failed.
This is the main.cpp :
#include <iostream>
#include "Morgan.h"
using namespace std;
int main()
{
Morgan morgObject;
morgObject.sayStuff();
return 0;
}
This is the Header file (Morgan.h):
#ifndef MORGAN_H
#define MORGAN_H
class Morgan
{
public:
Morgan();
void sayStuff();
protected:
private:
};
#endif // MORGAN_H
And this is the class (Morgan.cpp):
#include <iostream>
#include "Morgan.h"
using namespace std;
Morgan::Morgan()
{
}
void Morgan::sayStuff(){
cout << "Blah Blah Blah" << endl;
}
I really do not know what is going wrong, so any help would be appreciated. I copy and pasted the same code into a windows compiler and it worked fine, so it might just be the linux.
also when I run the main.cpp this is what shows:
"./geany_run_script.sh: 5: ./geany_run_script.sh: ./main: not found"
You don't compile .h files. Try g++ -Wall main.cpp Morgan.cpp
Your issue is that you are compiling C++ code with a C compiler (GCC). The command you are looking for is g++. The complete command that would compile your code is:
g++ -Wall -o run.me main.cpp Morgan.cpp
If a file is included (In your case the Morgan.h file, you do not need to explicitly compile it. )
#include<stdio.h>
#include<string.h>
void try(char s[])
{
if(strlen(s)>5)
{
puts("Error\n");
}
}
int main()
{
char string[10];
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s",&string);
try(string);
}
return 0;
}
Still can't find the error... try is a simple function and as always i am creating a func and calling it. compiler is giving error - (expected unqualified-id before 'try')
I suspect you are trying to compile your code as C++ rather than C. In C++, try is a reserved word (it is used in exception handling).
$ gcc test.c
$ g++ test.c
test.c:3:6: error: expected unqualified-id before 'try'
You can use -x to set the language explicitly (with either gcc or g++):
$ gcc -x c test.c
$ gcc -x c++ test.c
test.c:3:6: error: expected unqualified-id before 'try'
Try adding -x c to your invocation or renaming your file to main.c. It could be that gcc is choosing to compile your C file as C++ for some reason.