编译问题? [英] Compiler issue?

查看:47
本文介绍了编译问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在两个不同的文件中定义了具有相同名称的结构,

构建时出错,因为在通过指针访问时使用了错误的结构定义。


请参阅以下示例:

--------------------------------- --------------------------------

文件A:

typedef struct

{

uint8 a;

uint16 b;

} MyStruct_t;


int FuncA(无效)

{

MyStruct_t ObjA = {2,3};

MyStruct_t * PtrA = & ObjA;


printf(ObjA中元素b的偏移=%i \ n,& ObjA - & ObjA.b);

printf(PtrA中元素b的偏移=%i \ n,PtrA - & PtrA-> b);

}


--------------------------------

文件B:


typedef struct

{

uint8 a;

uint32 b;

} MyStruct_t;


int FuncB(vo id)

{

...

}

----------- -----------------------

在示例中,FuncA将显示ObjA = 2中元素b的偏移。和PtrA中元素b的偏移= 4。不同之处在于,当通过指针改变结构中的对齐方式访问元素b时,元素b被视为uint32。


有谁知道导致此错误的原因是什么?这是一个编译问题吗?如果是这样,这是一个已知的问题吗?

我正在使用带有Service Pack 1的Visual C ++ Express 2005编译器。


谢谢!

解决方案

我认为在两种情况下应该是4,因为(32位)编译器需要4个字节对齐。


raghu

如果先将所有地址转换为char *然后再进行减法会怎么样?


亲切的问候,


Jos


ps。文件B中的结构定义根本不在范围内。


没有编译器问题。


每个实现文件都是单独编译。因此,您可以在具有完全定义的每个文件中具有MyStruct_t。但是,当所有这些不同的定义到达需要变量和函数名称唯一的链接器时,您的构建将以重定义错误终止。


If a struct with the same name are defined in two different files,
something is wrong when building since the wrong struct definition is used when accessing via pointer.

See the following example:
-----------------------------------------------------------------
File A:
typedef struct
{
uint8 a;
uint16 b;
} MyStruct_t;

int FuncA(void)
{
MyStruct_t ObjA = {2, 3};
MyStruct_t *PtrA = &ObjA;

printf("Offset of element b in ObjA = %i\n", &ObjA - &ObjA.b);
printf("Offset of element b in PtrA = %i\n", PtrA - &PtrA->b);
}

--------------------------------
File B:

typedef struct
{
uint8 a;
uint32 b;
} MyStruct_t;

int FuncB(void)
{
...
}
----------------------------------
In the example FuncA will display, "Offset of element b in ObjA = 2" and "Offset of element b in PtrA = 4". The difference being due to element b being treated as a uint32 when accessed via a pointer changing the alignment in the structure.

Does anyone know what is causing this error? Is it a compiler issue? If so, is it a known issue?
I''m using Visual C++ Express 2005 compiler with service pack 1.

Thank you!

解决方案

I think it should be 4 in both cases as (32 bit)compiler takes 4 byts alignment.

raghu


What happens if you cast all addresses to char* first and then do the subtraction?

kind regards,

Jos

ps. The struct definition in file B isn''t in scope at all.


There''s no compiler issue.

Each implementation file is compiled separately. Therefore you can have a MyStruct_t in every file with completely definitions. However, when all these different definitions reach the linker who requires variable and function names to be unique, your build terminates with redefinition errors.


这篇关于编译问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆