Society of Robots - Robot Forum

Software => Software => Topic started by: Admin on August 29, 2007, 04:26:42 PM

Title: two files sharing variables
Post by: Admin on August 29, 2007, 04:26:42 PM
I have two different .c files compiled together and I want them to share a variable. What is the best way to do this? A header file?
Title: Re: two files sharing variables
Post by: h3ro on August 29, 2007, 04:31:59 PM
You can include .c files, no need to create a separate .h file (But it would be a bit cleaner)

Also, you can store them in a .txt file and have the .c files read from that file. Thats probably the best options if thats possible.
Title: Re: two files sharing variables
Post by: Admin on August 29, 2007, 04:34:32 PM
So the makefile requires me to specify all the .c files together . . . so I assumed they would work together but they arent . . .
Title: Re: two files sharing variables
Post by: Admin on August 29, 2007, 05:01:42 PM
Hmmmm so I figured out the problem . . .

Apparently if you add .c files as a dependency to a makefile to compile together, they DO NOT LINK variables. Only functions . . .

So I took your suggestion and did an #include. This fixed it and now the .c files share variables.

Argggg . . . is this a bug with the makefile thingy?
Title: Re: two files sharing variables
Post by: JesseWelling on August 29, 2007, 06:48:16 PM
I assume you mean a global variable used in two different .c files?

You need to use the keyword 'extern' meaning that the same named variable is in some other scope (non file scope)

http://www.faqs.org/docs/learnc/x784.html

You can also extern (used as a verb here ;) ) functions that are not declared in a .h file.