Re: structures with the same name are messed up

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 2014.04.25 at 12:17 +0200, Gyorgy Kovesdi wrote:
> Hi,
> 
> I got a strange behavior having different structures with the same name in 
> different cpp sources. AFAIK they must be independent.
> Actually it happened in two different libraries using a template class from a 
> third library.
> 
> It can be reproduced with the following simple source:
> Let's have a header file with this template class:
> 
> template <typename T>
> struct Checker
> {
>     int mySize() { return sizeof(T); }
> };
> 
> It just returns the size of the template parameter.
> Let's have the following cpp source (let's say a.cpp):
> 
> struct test
> {
>     int a;
> };
> 
> int test_a()
> {
>     return Checker<test>().mySize();
> }
> 
> The function test_a() must return 4 in this case.
> Also let's have another file (let's say b.cpp) with a slightly different 
> content:
> 
> struct test
> {
>     int a[10];
> };
> 
> int test_b()
> {
>     return Checker<test>().mySize();
> }
> 
> The function test_b() must return 40 in this case.
> 
> Let's compile them independently: now we have the functions test_a() and 
> test_b() in two different object files. Calling them separately we have the 
> requested result. But if they are linked together, the result depends on the 
> optimization:
> 
> - Optimized case (-O1 or higher):
> The function test_a() returns 4
> The function test_b() returns 40
> 
> - Not optimized case (-O0):
> The function test_a() returns 40
> The function test_b() returns 40
> 
> I used different gcc versions from 3.4 to 4.8 with the same result.
> The problem is caused by having two different functions with the same name: 
> Checker<test>::mySize(). However, the parameter 'test' differs in these cases, 
> the linker treats them equal without any message, causing wrong behavior. The 
> optimized case probably works well because of inlining.
> It means dependency between the two libraries I mentioned at the beginning: 
> they must not use the same name, which is at least very strange for me.
> 
> How can I write such libraries if I want to have reliable code? I have no idea 
> about it, any help would be appreciated.

You're violating the "one definition rule". It states that you can
define the same struct in different translation units, provided it
consist of the same sequence of tokens, otherwise the behavior is
undefined as in your example.

-- 
Markus




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux