Game Development Reference
In-Depth Information
This very basic example shows that we can declare functions inside code files. This file itself does
not do anything interesting; it does not contain the entry point to our program. We would like to be
able to call this function from other places in our code base. To be able to do this we must create a
header file that contains a function declaration. Listing 7-2 shows our HelloWorld.h file.
Listing 7-2. HelloWorld.h
#pragma once
void HelloWorld();
The header file is very simple and contains our function declaration.
The #pragma once is necessary in header files to inform the compiler that we only want to include
this file a single time. If we do not have this line at the beginning of our header file we will suffer from
compile errors as the function definitions will occur more than once.
Note #pragma once is a modern compiler directive that is not supported by older compilers. In the
past, header files would have include guards instead. Include guards use #ifndef , #define , and #endif
to wrap header files and prevent the code from being included more than once. This is less efficient than
#pragma once , which can tell the compiler to skip opening the file and reduce compile times if it has been
processed before.
Now that we have a header file and a source file we will be able to use this to call our function from
other files. Listing 7-3 shows how we can do this.
Listing 7-3. Calling HelloWorld from _tmain
#include "stdafx.h"
#include "HelloWorld.h"
int _tmain(int argc, _TCHAR* argv[])
{
HelloWorld();
return 0;
}
We can see from this example that our source files can now be kept in a much neater and more
maintainable state. We simply include the HelloWorld.h file and we have access to the function that
it contains. As we move forward we will be using source and header files extensively. This simple
example covers all of the necessary details to be able to use these in our projects.
 
Search WWH ::




Custom Search