20

I guess this is embarrassing if I told you I cant get this to compile. would you please help me:

#include<memory>
using namespace std;

int  main()
{
    std::unique_ptr<int> p1(new int(5));
    return 0;
}
$ gcc main.cpp 
main.cpp: In function ‘int main()’:
main.cpp:6:2: error: ‘unique_ptr’ was not declared in this scope
main.cpp:6:13: error: expected primary-expression before ‘int’
main.cpp:6:13: error: expected ‘;’ before ‘int’

$ gcc --version
gcc (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
rahman
  • 4,820
  • 16
  • 52
  • 86
  • 2
    `gcc` is almost never used without passing some options. Try at least `g++ -std=c++0x -pedantic main.cpp`. – Luc Danton Mar 19 '12 at 07:45
  • 5
    why do you use std:: if you have using namespace std; anyways? – Azrael3000 Mar 19 '12 at 07:46
  • thanks. it worked. 1- why don't you post an answer so that i can mark it as true. 2-while you are on it, would you please give me a short reason why gcc is never used(and g++ used instead) or perhaps link to a reference? thanks – rahman Mar 19 '12 at 07:52
  • @rahman: `gcc` = C, `g++` = C++. – AusCBloke Mar 19 '12 at 07:58
  • @AusCBloke gcc stands for Gnu Compiler Collection , it auto-detects language based on file extension. Although the use of `g++` is important if you're invoking it solely as the linker, when it can't deduce from extension. – M.M Feb 17 '17 at 09:55

2 Answers2

32

This is just a guess.

Most likely you compiled your program like this (or similarly) :

g++ main.cpp

If you did, then the problem is that g++ uses c++03 as default. To use c++11 features (and std::unique_ptr), you need to use newer version of c++ :

g++ -std=c++11

or

g++ -std=c++14

and I would recommend to use also -Wall -Wextra -pedantic.

BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • I am facing the same problem, but `-std=c++11` flag is enabled and all required headers are included. Can't get what's wrong: https://gist.github.com/canadien91/2ba3f9576823159c2d52 – Montreal Jun 22 '15 at 20:55
  • 1
    for future reference: @Montreal #include – Stuck Feb 16 '17 at 10:40
  • @Stuck, hmm, in my gist is included. But I don't remember now when I have added this. – Montreal Feb 16 '17 at 20:47
  • actually the gist link for me is a 404 error, so I only had a guess.. because I experienced the same problem. For me it would have been helpful to get that hint here beneath your comment. – Stuck Feb 16 '17 at 22:42
  • 1
    Worth noting, the [std::make_unique](http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique) function requires c++14 – Daniel Stevens Sep 12 '17 at 01:36
4

If you are using Code::Blocks, go to Settings > Compiler > Global compiler settings > Compiler settings and look for the Have g++ follow the C++11 ISO C++ language standard [-std=c++11] and check it!

(Code::Blocks will add the -std=c++11 for you when compiling)

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
Sevener
  • 41
  • 1