8

I got some quite strange errors compiling code under gcc. It tells me that std::function does not exist.

I can recreate the error with the following code:

#include <functional>
#include <stdio.h>

void test(){ printf ("test"); }

int main() {
    std::function<void()> f;
    f = test;
    f();
}

If I run gcc (from cygwin): (my error message was German, so i translated it. It may be sound different on a English gcc)

$ gcc test.cpp
test.cpp: in function "int main(): 
test.cpp:7:3: Error: "function" is not an element of "std"« 
test.cpp:7:25: Error: "f" was not defined in this scope

With MSVC it compiled successfully. Please tell me what I am doing wrong in my code.

Johannes

Marcin
  • 46,667
  • 17
  • 117
  • 197
EGOrecords
  • 1,869
  • 2
  • 19
  • 33

2 Answers2

18

Compile it as:

g++ test.cpp -std=c++0x

-std=c++0x is needed because you're using C++11 features, otherwise g++ test.cpp is enough.

Make sure you've latest version of GCC. You can check the version as:

g++ --version
Nawaz
  • 341,464
  • 111
  • 648
  • 831
  • 1
    "If you use gcc test.cpp, then it assumes C program!" Not true. gcc infers the language from the file extension. If it assumed a C program, the error message would be quite different. `std::function` would be a syntax error in C. It wouldn't produce a message about `function` not existing in the `std` namespace. What is true is that `gcc` (unlike `g++`) doesn't automatically link against the c++ standard library, so you'd get linker errors if you don't specify the appropriate -l flag manually. – sepp2k Jun 13 '12 at 15:42
3

You need to compile in C++ mode, and in C++11 mode. So you need g++ and the -std flag set to c++0x.

g++ test.cpp -std=c++0x

You can also use -std=c++11 from gcc 4.7 onwards.

juanchopanza
  • 216,937
  • 30
  • 383
  • 461