PDA

View Full Version : C++: What's wrong with this header file?


Karim
01-27-2005, 01:04 AM
/***** common.h *****/

void open_database(ofstream &out);
Everything works if I don't pass anything to the function otherwise the compiler screams with:

In file included from recordsub.cpp:4:
common.h:3: `ofstream' was not declared in this scope
common.h:3: `out' was not declared in this scope
common.h:3: variable or field `open_database' declared void
recordsub.cpp: In function `int main()':
recordsub.cpp:24: `open_database' cannot be used as a function
/***** common.cpp *****/

#include iostream
#include fstream
#include "common.h"

using namespace std;

void open_database(ofstream &out)
{
out.open ("submissions", ios::binary);

if (out.fail())
{
cout << "Error: The database did not open..." << endl;
}
return;
}
/***** recordsub.cpp *****/

#include cstdlib
#include fstream
#include iostream
#include "common.h"

#define MAX_NAME_LEN 50

using namespace std;

struct Record
{
char name[MAX_NAME_LEN + 1]; //citizen tax data
int sin;
double income;
streampos left; //links to left and right subtrees
streampos right;
};

int main()
{
ofstream out;

open_database(out);

out.close();

return 0;
}
I thought it might have been something wrong with my makefile but it works as long as I don't include any arguments in the header file. I figure it's something pretty simple but do you think I can see it?

sabotai
01-27-2005, 01:43 AM
Shouldn't the includes for iostream and fstream be in the header file instead of the .cpp file? If you don't put them in the header, then the compiler doesn't know what ofsteam is for the parameter type. At least, I don't think it would.

Karim
01-27-2005, 02:18 AM
Thanks, sab. The document I was working from only had simple examples so none of the sample header files had any #includes.

Marc Vaughan
01-27-2005, 05:49 AM
One thing to bear in mind for the future which might help with compile speeds if you work on large projects is 'forward declarations of classes'.

If a class is referenced in a header but its content isn't required for compilation (generally speaking if you're using pointers to it in the class functions or data) then you can forward declare a class.

This is simply telling the compiler "don't panic the class exists and the linker will find it" and allows you to avoid having unrequired includes in header files.

To do this use the syntax:

class MY_CLASS;

This indicates that a class called MY_CLASS exists and not to worry about its contents.

(please note this is a basic overview of how 'forward declarations work' and isn't meant to be 100% correct in low level stuff to do with compilers)