Archived

This topic is now archived and is closed to further replies.

static variables, in c/linking (help needed)

This topic is 5010 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

This is a problem Im having in a bigger program im writing, however to simplify the explanation Ive created a small project which reproduces the problem more simply. I have 3 files: main.c
#include <stdio.h>
#include "module.h"

int main()
{
	printf("g is %d\n",g);
	change_g();
	printf("g is %d\n",g);
	
	return(0);
} 
module.c
  
#include "module.h"

void change_g()
{
	g=1;
} 
and finally module.h
#ifndef MODULE_H
#define MODULE_H
static int g;
void change_g();
#endif
(as you can see im trying to keep the code as simple as possible) If I compile the program like so:
g++ main.c module.c -o main
It compiles alright however when I run it I get the following output:
g is 0
g is 0
However if I change the main.c file to look like this:
#include <stdio.h>
#include "module.h"
#include "module.c"

int main()
{
	printf("g is %d\n",g);
	change_g();
	printf("g is %d\n",g);
	
	return(0);
} 

...ie if I compile it all into the 1 object file, the program functions allright:
g is 0
g is 1
why is this? and how can I change it so it works? I really want to learn something here so can someone please give me a detailed explanation. thanks. [edited by - nodger on March 26, 2004 7:24:09 PM]

Share this post


Link to post
Share on other sites
When a variable at the global scope is declared static in a header, it means that every object file that includes the header gets a different copy of that variable. What you want to do is declare the variable as extern in the header file. Then in one source file declare it the variable again (without extern or static) to allocate storage for it. The extern''d declaration tells the object files that you''re going to declare the variable in some object file.

Share this post


Link to post
Share on other sites
Declare the static variable inside your C file and in the .h file declare it as extern. this should fix it. The problem occurs becos 2 obj files are created (main.obj and module.obj) and both have the variable defined (bcos ur declaration was in the module.h file and its being used by both the c files) and hence it causes problems when linking the 2 obj files. And never include a .c or .cpp file in another .c/.cpp file.
hope this helps

Share this post


Link to post
Share on other sites
quote:
Original post by krad7
Declare the static variable inside your C file and in the .h file declare it as extern. this should fix it.

No. The declaration in the source file should be without the static linkage specifier. It''s illegal to redefine an extern variable with static linkage.

Share this post


Link to post
Share on other sites