This question already has an answer here:
I have this code:
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
writeFile();
}
int writeFile ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
Why is this not working? it gives me the error:
1>------ Build started: Project: FileRead, Configuration: Debug Win32 ------
1> file.cpp
1>e:\documents and settings\row\my documents\visual studio 2010\projects\fileread\fileread\file.cpp(8): error C3861: 'writeFile': identifier not found
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
and this is just a simple function. I'm using Visual Studio 2010.
There are two solutions to this. You can either place the method above the method that calls it:
Or declare a prototype:
You need to declare the prototype of your
writeFile
function, before actually using it:Your
main
doesn't know aboutwriteFile()
and can't call it.Move
writefile
to be beforemain
, or declare a function prototypeint writeFile();
beforemain
.This is a place in which C++ has a strange rule. Before being able to compile a call to a function the compiler must know the function name, return value and all parameters. This can be done by adding a "prototype". In your case this simply means adding before
main
the following line:this tells the compiler that there exist a function named
writeFile
that will be defined somewhere, that returns anint
and that accepts no parameters.Alternatively you can define first the function
writeFile
and thenmain
because in this case when the compiler gets tomain
already knows your function.Note that this requirement of knowing in advance the functions being called is not always applied. For example for class members defined inline it's not required...
In this case the compiler has no problem analyzing the definition of
bar
even if it depends on a functionbaz
that is declared later in the source code.Switch the order of the functions or do a forward declaration of the writefiles function and it will work I think.
The function declaration int writeFile () ; seems to be missing in the code. Add int writeFile () ; before the function main()