If you have a function in one .cpp file that you want to use in another .cpp file, you have to prototype it in the .cpp file you want to use it in.
You have two options:
a. Use a header file
b. Use
extern
a.
1 2 3 4 5 6
|
#ifndef _HEADER_H_
#define _HEADER_H_
return type function name(parameter list) attributes;
#endif
|
The #ifndef... #define... #endif stuff is called a
header guard. It avoids problems that can be brought about by including a file twice, such as multiple definitions of the same function.
A working example would be
main.h
1 2 3 4 5 6 7 8 9
|
#ifndef _MAIN_H_
#define _MAIN_H_
#include <stdio.h>
/* Forward declarations */
int main(int, char**); /* main: entry point */
void die(const char*); /* die: print error message and then die */
#endif
|
main.c[pp]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include "main.h"
int main(int argc, char** argv) {
if (argc < 2)
die("Usage: main arg1 [arg2 .. argn]\n"); /* Compiler knows how to resolve die() */
return 0;
}
void die(const char* s) {
fprintf(stderr, "%s\n", s);
exit(1);
}
|
b.
Is simpler, but with a header if you want to change a function, you only change it once or twice. With
extern
, you change it in every file that uses it.
1 2 3 4 5 6 7 8 9 10 11 12
|
extern return type function name(parameter list) attributes;
Working code using extern:
main.c[pp]
[code]extern void die(const char*);
int main(int argc, char** argv) {
if (argc < 2)
die("Usage: main arg1 [arg2 .. argn]\n"); /* Compiler knows how to resolve die() */
return 0;
}
|
die.c[pp]
1 2 3 4 5 6 7
|
extern void exit(int);
void die(const char* s) {
fprintf(stderr, "%s\n", s);
exit(1);
}[/
|
"attributes" is optional, e.g.
int* return_an_int_pointer(void) const;
.
Omitting parameter names in
function declarations is optional. Personally I tend to leave them out because then if I decide a name is not expressive enough (e.g.
const char* s
doesn't tell you want s does) or I change what a parameter is used for, I only have to rename it in one place.
Omitting parameter names in
function definitions is not optional. You can't omit them.
A function declaration is where you declare the function's return type, name and parameter list. A definition is where you write the function body.