0

I'm at a loss - i'm just getting into C++ and for some reason this is not working out for me. So i'm using Netbeans, and i've got the following main file:

#include <cstdlib>

#include "functions.h"

using namespace std;

int main(int argc, char** argv) {

    f("help");

    return 0;
}

Functions.h file:

#include <string>

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

void f( string a );

#endif

and Functions.cpp file:

#include "functions.h"

void f( string a ) {
    return;
}

So, long story short, it doesn't compile. It says it can't understand the string variable? I don't get it, i tried moving the include for string all over the place but nowhere seems to help. What do i do?

Rapptz
  • 20,807
  • 5
  • 72
  • 86

3 Answers3

2

If you are attempting to use std::string, you have to #include <string> in your functions header, and call it std::string,since it is in the std namespace.

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include <string>

void f( std::string a );

#endif

See this related post and also why is 'using namespace std' considered bad practice in C++?

Community
  • 1
  • 1
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
2

You need to include string header file in Functions.h, also tell compiler that string is from std namespace.

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include <string>
void f( std::string a );

#endif

Functions.cpp file:

#include "functions.h"

void f( std::string a ) {
    return;
}

Better practice is to pass string by const reference

void f(const std::string& a ) {
    return;
}

See Why is 'using namespace std;' considered a bad practice in C++?

Community
  • 1
  • 1
billz
  • 44,644
  • 9
  • 83
  • 100
  • Can I get around this by writing that "using namespace std;" line in my other files? Or is it good practice to write it in? – user1288167 Feb 05 '13 at 23:46
  • 1
    Yes you can but that's not good program practice. See my updated answer regarding `using namespace std;` – billz Feb 05 '13 at 23:46
  • 2
    @user1288167: Please don't get in to the bad habit of `using namespace std`. It will only cause you and your colleagues grief. – John Dibling Feb 05 '13 at 23:48
  • Ok, i'm not opposed to learning to not use it, but why does it cause grief? – user1288167 Feb 05 '13 at 23:49
  • 1
    @user1288167: Because of name ambiguity. See the link provided in bilz's answer for a pretty good explanation. – John Dibling Feb 05 '13 at 23:54
0

Include the standard header: <string>

#include <string>
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234