Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 11 months ago.
What is the correct way to access variables/definitions/objects across multiple files?
I am trying to tidy up my code by splitting it off into different files with associated functions but I am having some trouble getting it all setup correctly
If I want to use the defined serial port across different files what would be the correct way to define this? If I do a Serial PC(USBRX, USBTX); in main.cpp I cannot access it in another file with an error PC not defined. If I define it in both of course I get a multiple define issue
Not sure what the 'proper' way to do this is.
2 Answers
10 years, 11 months ago.
Or you declare:
extern int xyz;
in the header file that you include in every .c file, and you define:
int xyz;
in exactly one .c file. the declaration and definition do not bite each other.
Is there a way I can write a function that depends on say Serial PC being defined but be able to determine whether this is the case and if not to define it? Perhaps this isn't the correct way around the problem? I was thinking if I wanted to write a standalone function that uses say the serial port always based on the USB RX and TX, how would I reference this? Would I have to impose that it be setup as 'PC'?
posted by 30 Aug 201310 years, 11 months ago.
you can create a header file like main.h and go like this: suppose I want a variable 'xyz' to be shared across various file then
main.h code below
- ifdef MAIN_C_ int xyz; Here we define the variable
- else extern int xyz; Here we declare the variables for other c file to use...
Now in main.cpp simply define this as
- define MAIN_C_
- include main.h
So now if you want to use it in any other .cpp file simpy include main.h
Hope this helps
Thanks for the responses, I have it working with a variable xyz however I cannot get it working with serial connection definition. Either way I get "Symbol PC multiply defined (by stuff.cpp.o and main.cpp.o)." In main I am trying to set the baud rate, it is defined in hardware.h, stuff.cpp includes hardware.h but no reference to PC.
My bad, I had: extern Serial PC(USBTX,USBRX); Instead of: extern Serial PC;
posted by Tom Davies 29 Aug 2013