Global variable conflict.

S

Shinu George

I have two files like given below:

/* File 1 */
#include <stdio.h>
#include <stdlib.h>

void tf(void);

int i;

int main(void)
{
i = 10;
tf();

return EXIT_SUCCESS;
}

/* End File 1 */

/* File 2 */
#include <stdio.h>

int i = 48;


void tf(void)
{
printf("%d\n", i);
}


/* End File 2 */


The observed behaviour is that the "printf" always prints the value of i as 10.

Two questions:

1 (for clc). Is the above code standards (ANSI) compliant?
2 (for cup). How do I get the linker to "see" the i with value 48 on Solaris?

Thanks and regards,
Shinu
 
E

Emmanuel Delahaye

In said:
I have two files like given below:

/* File 1 */
#include <stdio.h>
#include <stdlib.h>

void tf(void);

int i;

int main(void)
{
i = 10;
tf();

return EXIT_SUCCESS;
}

/* End File 1 */

/* File 2 */
#include <stdio.h>

int i = 48;

You can't have two global scope variables with the same name in the same
project. Your linker should warn you about that.
void tf(void)
{
printf("%d\n", i);
}


/* End File 2 */


The observed behaviour is that the "printf" always prints the value of i
as 10.

Won't link at home.
Two questions:

1 (for clc). Is the above code standards (ANSI) compliant?

No.

If you insist to have these global scope variables, you must reduce their
scope to the file with 'static'.
 
E

E. Robert Tisdale

Shinu George wrote:

[snip]
> cat file2.h
#ifndef GUARD_FILE2_H
#define GUARD_FILE2_H 1
#include <stdio.h>
#include "file2.h"

extern int i;

void tf(void);

#endif//GUARD_FILE2_H
> cat file2.c
/* File 2 */
#include "file2.h"

int i = 48;

void tf(void) {
printf("%d\n", i);
}

/* End File 2 */
> cat file1.c
/* File 1 */
#include "file2.h"
#include <stdlib.h>

int main(int argc, char* argv[]) {
tf();
i = 10;
tf();

return EXIT_SUCCESS;
}

/* End File 1 */
> gcc -Wall -std=c99 -pedantic -O2 -o file file1.c file2.c
> ./file
48
10
 
S

Shinu George

Alan Balmer said:
Yes. The system initializes the i in file 2 at load time. At
execution, main overwrites the initialization.

Perhaps if you explained what you're trying to accomplish, someone
could suggest a better approach.

Accomplish? Nothing. This question was asked of me at an interview
(with a large database company whose name begins with "O". In
India.). Essentially they asked me the second question with reference
to the linker. Confused the hell out of me.

Didn't get through the interview, anyway.

Thanks,
Shinu
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top