Rob, I suspect you are actually getting a linker error, although that may not be obvious. As each individual file is compiled, the compiler reads that file and the included file and it successfully creates a memory object 'c'. Neither cpp file knew of the existance of the other cpp file. Then, when the two files were linked together to try to form a program, it found these two things called 'c' but it could not tell that you intended them to be one in the same, so it errors out - multiple definitions.
To bend your code to demonstrate what steve is recommending.
//main.cpp
#include "functions.h"
int main() {
c = 3; // c is defined elsewhere, as 'functions.h' tells us
printc(); // this function is also defined elsewhere
}
//end main.cpp
//functions.cpp
#include "mbed.h"
char c; // c is 'owned' by this file
void printc() { // printc is also owned by this file
printf("c is %i\r\n", c);
}
//end functions.cpp
//functions.h is the "interface" to functions.cpp
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
extern char c; // indicate that c exists somewhere
extern void printc(); // indicate that printc exists somewhere
#endif // FUNCTIONS_H
So in this variation, main.cpp learns of c and printc from the functions.h header file. Also note that functions.cpp is the only one that needed mbed.h. So each file gets enough information to do what it needs, but not more.
Hi, I'm trying to consolidate the basics of modular programming techniques, but I'm unsure why the #ifndef compiler directive has no effect....
I've created three files in a project:
But I always get a compiler error saying that multiple definitions of char c are attempted. Surely if the #ifndef directive is working ok then the header file would only be invoked once...? Ultimately I want to define all my global mbed objects, variables, #defines and function prototypes in header.h, but I can only do this if it's possible to ensure that the compiler only looks at header.h once. Any ideas?