Author Topic: two files sharing variables  (Read 2421 times)

0 Members and 1 Guest are viewing this topic.

Offline AdminTopic starter

  • Administrator
  • Supreme Robot
  • *****
  • Posts: 11,663
  • Helpful? 169
    • Society of Robots
two files sharing variables
« 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?

Offline h3ro

  • Full Member
  • ***
  • Posts: 110
  • Helpful? 0
Re: two files sharing variables
« Reply #1 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.

Offline AdminTopic starter

  • Administrator
  • Supreme Robot
  • *****
  • Posts: 11,663
  • Helpful? 169
    • Society of Robots
Re: two files sharing variables
« Reply #2 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 . . .

Offline AdminTopic starter

  • Administrator
  • Supreme Robot
  • *****
  • Posts: 11,663
  • Helpful? 169
    • Society of Robots
Re: two files sharing variables
« Reply #3 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?

Offline JesseWelling

  • Expert Roboticist
  • Supreme Robot
  • *****
  • Posts: 707
  • Helpful? 0
  • Only You Can Build A Robot!
Re: two files sharing variables
« Reply #4 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.

« Last Edit: August 29, 2007, 06:52:14 PM by JesseWelling »

 


Get Your Ad Here

data_list