473,545 Members | 1,471 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

when should multiple definitions of global variables trigger link time errors?

Hi!

When are multiple definitions of global variables with the same name
considered legal in C, and how is it different from C++? It appears
that in terms of assembly language, some C definitions are translated
to "weak" symbols, in which case multiple definitions are merged by the
linker, while some become "normal" symbols, triggering linker errors in
case they are defined more then once. Is it true that in C++, multiple
definitions are always disallowed?

This code (2 translation units) compiles with gcc -ansi, but triggers
linker errors with g++:

//weak1.c (or weak1.cpp):
#include <stdio.h>
int a[5];
void f();
int main()
{
printf("&a=%p\n ",a);
f();
}

//weak2.c (or weak2.cpp):
#include <stdio.h>
int a[10];
void f()
{
printf("f: &a=%p\n",a);
}

Compiled with gcc, it prints:

&a=0x80495e0
f: &a=0x80495e0

- showing that the definitions `int a[5]' and `int a[10]' were merged.
A symbol table listing shows that the dimension of a[] in the linked
binary is 10. Adding initializers to the definitions, for example,
triggers linker errors in C.

Thanks in advance!
Yossi

Mar 4 '06 #1
8 3284
yo***********@g mail.com wrote:
Hi!

When are multiple definitions of global variables with the same name
considered legal in C,
Never.
and how is it different from C++?
Not topical on comp.lang.c, but I would expect it to be the same.
It appears
that in terms of assembly language, some C definitions are translated
to "weak" symbols, in which case multiple definitions are merged by the
linker, while some become "normal" symbols, triggering linker errors in
case they are defined more then once.
That may be the case on some implementations , but it is not true on all.
On one of the C implementations I use regularly it will produce a link
time error on multiple definitions of a symbol, on another it won't.
That's the wonder of Undefined Behaviour, *anything* can happen.
Is it true that in C++, multiple
definitions are always disallowed?

This code (2 translation units) compiles with gcc -ansi, but triggers
linker errors with g++:
Use different options with gcc and you may get different results.
//weak1.c (or weak1.cpp):
#include <stdio.h>
int a[5];
<snip>
//weak2.c (or weak2.cpp):
#include <stdio.h>
int a[10];
<snip>

Undefined behaviour in C. Anything can happen.

<snip>
binary is 10. Adding initializers to the definitions, for example,
triggers linker errors in C.


So will selecting the correct option in some versions of gcc.
Specifically the -fno-common option. You should also use -pedantic if
you want gcc to be a fully compliant C compiler, and looking at and
enabling the other warnings would also be a good thing.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
Mar 4 '06 #2
On 4 Mar 2006 04:34:34 -0800, in comp.lang.c , yo***********@g mail.com
wrote:
Hi!

When are multiple definitions of global variables with the same name
considered legal in C,
Never, there can be only one definition of any object.

Multiple global declarations are fine though, so long as they're the
same. Your example with two different declarations of 'a' should have
triggered a warning from your compiler, and is I believe undefined
behaviour.
and how is it different from C++?


No idea.

Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Mar 4 '06 #3
On Sat, 04 Mar 2006 14:44:54 +0000, in comp.lang.c , Flash Gordon
<sp**@flash-gordon.me.uk> wrote:
yo***********@ gmail.com wrote:
Hi!

When are multiple definitions of global variables with the same name
considered legal in C,

Use different options with gcc and you may get different results.
//weak1.c (or weak1.cpp):
#include <stdio.h>
int a[5];


<snip>
//weak2.c (or weak2.cpp):
#include <stdio.h>
int a[10];


<snip>

Undefined behaviour in C. Anything can happen.


IIRC these are declarations and tentative definitions. The fact that
they're different is indeed UB but its not illegal to have several
tentative definitions.
Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Mar 4 '06 #4
> IIRC these are declarations and tentative definitions. The fact that
they're different is indeed UB but its not illegal to have several
tentative definitions.


Could you please explain that? If I understand correctly, you say that
`int a[5]' in both translation units are "declaratio ns and tentative
definitions", but I don't understand exactly what that means. Does it
mean that multiple definitions are going to be allowed by the compiler,
but the behaviour is only defined when they are identical (if so,
identical on what level)? Which definitions are tentative?

TIA,
Yossi

Mar 4 '06 #5
Thanks!

I use -Wall -ansi -pedantic. I assumed it does the trick. Forgive me if
it's the wrong place to ask, but while we're at it - what are the
correct options to ask gcc for it's fullest standard compliance? It
looks like -ansi -pedantic are not enough.

Or is it standard compliant to ignore multiple definitions of a[],
especially if I fixed them to define the same array size? Do any
multiple definitions trigger undefined behaviour, or only different
ones?

Mar 4 '06 #6
Mark McIntyre <ma**********@s pamcop.net> writes:
On Sat, 04 Mar 2006 14:44:54 +0000, in comp.lang.c , Flash Gordon
<sp**@flash-gordon.me.uk> wrote:
yo***********@ gmail.com wrote:
Hi!

When are multiple definitions of global variables with the same name
considered legal in C,

Use different options with gcc and you may get different results.
//weak1.c (or weak1.cpp):
#include <stdio.h>
int a[5];


<snip>
//weak2.c (or weak2.cpp):
#include <stdio.h>
int a[10];


<snip>

Undefined behaviour in C. Anything can happen.


IIRC these are declarations and tentative definitions. The fact that
they're different is indeed UB but its not illegal to have several
tentative definitions.


This is only true within the same translation unit. A tentative
definition still causes the object to be defined at the end of the
unit. Since both units define it, this causes UB regardless of
disagreement on type.

-Micah
Mar 4 '06 #7
yo***********@g mail.com wrote:

Could you please explain that? If I understand correctly, you say that
`int a[5]' in both translation units are "declaratio ns and tentative
definitions", but I don't understand exactly what that means.


A tentative definition is a declaration that will be interpreted as a
definition only if no other (non-tentative) definition appears in the
translation unit. In your case, there are no other definitions in the
translation units, so both of the tentative definitions are, in fact,
interpreted as definitions, resulting in multiple definitions for the
same object, which results in undefined behavior. The code is
incorrect, but there's no obligation for the compiler/linker to diagnose
it.

-Larry Jones

I've got an idea for a sit-com called "Father Knows Zilch." -- Calvin
Mar 4 '06 #8
On Sat, 04 Mar 2006 21:13:54 GMT, in comp.lang.c ,
la************@ ugs.com wrote:
yo***********@ gmail.com wrote:

Could you please explain that? If I understand correctly, you say that
`int a[5]' in both translation units are "declaratio ns and tentative
definitions", but I don't understand exactly what that means.


A tentative definition is a declaration that will be interpreted as a
definition only if no other (non-tentative) definition appears in the
translation unit.


Agh, for some reason i had it in my head that the rule was across all
TUs.
Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Mar 4 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
6721
by: SilverShadow | last post by:
Hello, I'm having trouble with something that may be easily remedied. I use Cantera running on Python. I need to make multiple "Reactor()" objects and have them assigned a different (user defined) name. For example: reactors = for reac in reactors: reac = Reactor()
20
6934
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt = document.getElementById('hometab'); Has anyone ever seen anything like this before, or am I dreaming?
9
429
by: yossi.kreinin | last post by:
Hi! When are multiple definitions of global variables with the same name considered legal in C, and how is it different from C++? It appears that in terms of assembly language, some C definitions are translated to "weak" symbols, in which case multiple definitions are merged by the linker, while some become "normal" symbols, triggering...
0
1897
by: capes | last post by:
have functions in my cell model calling CVODE for each time step. When I build the application I get a number of link errors: \cardiacsimulator.o Release\ccardiaccell.o Release\ccelldata.o Release\cgapjunction.o Release\cheart2d.o Release\integrator.o -o D:\kp\programs\cardiacsimulator\Release\cardiacsimulator.exe Release\integrator.o:...
10
3481
by: subramanian100in | last post by:
Suppose I declare a global variable int g; in two different files say a.c which has main() and b.c When I compile them to build an executable under gcc in Redhat Linux with the command gcc -std=c99 -pedantic -Wall -Wextra a.c b.c
6
2404
by: Gaijinco | last post by:
I'm having a weird error compiling a multiple file project: I have three files: tortuga.h where I have declared 5 global variables and prototypes for some functions. tortuga.cpp where I implement all of the functions of tortuga.h main.cpp where I use the functions implemented in tortuga.cpp I create the objetc file without problem. But...
6
27528
by: stenasc | last post by:
Hi, In a file test1.c, in have the two functions f1 and f2. These are declared in the header file t1.h. I want to call these functions in another file subprog.c, which contains the function call_funcs. I have included the header file t1.h in subprog.c. Using gcc, I can compile and get subprog.o without any problems. However, when I try...
20
12700
by: teddysnips | last post by:
Weird. I have taken over responsibility for a legacy application, Access 2k3, split FE/BE. The client has reported a problem and I'm investigating. I didn't write the application. The AutoExec macro calls a function "InitApplication" which, in turn, calls a function to set the value of a global string variable
4
2361
by: icarus | last post by:
global_vars.py has the global variables set_var.py changes one of the values on the global variables (don't close it or terminate) get_var.py retrieves the recently value changed (triggered right after set_var.py above) Problem: get_var.py retrieves the old value, the built-in one but not the recently changed value in set_var.py. What...
0
7465
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7805
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7752
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5969
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5325
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4944
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1878
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
701
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.