problem with header files

Hi,

i'm trying to learn to use header files. For this purpose, i created the following files, and linked them together (i use Codeblocks):

main.cpp :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include "mennyi.h"
#include <string>

using namespace std;

int main()
{
    int a,b,c;
    string s;
    cin >> a;
    cin >> b;
    cin >> s;
    c = Mennyi(a,b,s);
	cout << c << endl;
	return 0;
}



mennyi.cpp :

1
2
3
4
5
6
7
8
9
10
#include "mennyi.h"
#include <string>
#include <iostream>

int Mennyi(int a,int b,string s)
    {
        std::cout << s;
        return a * b;
    }



mennyi.h :

1
2
3
4
5
6
7
#ifndef MENNYI_H
#define MENNYI_H
#include <string>

int Mennyi(int,int,string);

#endif 


When i try to compile any of these files (they are of course part of the same project), the compiler says, that 'string' is not declared. All three files are in the same directory. Where should i declare 'string' ?
have you tried putting "using namespace std;" in each of the files?

I see that you have it in main.cpp- try putting it in the other two as well.
closed account (z05DSL3A)
It is recommended not to use "using namespace …" directives in header files as it causes namespace pollution. It is far better to use scope resolution in your header files.

1
2
3
4
5
6
7
#ifndef MENNYI_H
#define MENNYI_H
#include <string>

int Mennyi(int,int,std::string);

#endif 


namespace pollution: Term used to describe what happens when all the names of classes and functions are placed in the global namespace. Large programs that use code written by multiple independent parties often encounter collisions among names if these names are global.
writing 'using namespace xy' in .cpp files other than main.cpp causes namespace pollution too ?

Btw, both solutions worked for me, thanks for the fast answer.
closed account (z05DSL3A)
As I understand it, as long as "using namespace …" directives are used after your your #include directives there will not be a problem as it is only in the scope of that file. Header files are included into the scop of other files.
Topic archived. No new replies allowed.