为什么我的编译警卫preventing多重定义的夹杂物? [英] Why aren't my compile guards preventing multiple definition inclusions?

查看:152
本文介绍了为什么我的编译警卫preventing多重定义的夹杂物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这是由多于一个的* .c源文件包含的头文件x.h。
这个头文件有一定的结构变量定义的。

我已经把多次包含prevention守在头文件的开头:

 的#ifndef X_H
#定义X_H
...
..
//头文件声明。定义和。
#ENDIF // X_H

在建筑,我得到有关多重定义链接错误。我理解这个问题。


  1. 不会在头文件的顶部,因为我有,prevent头文件了XH多个包裹,从而多包容prevention后卫避免在那里的变量的多个定义XH?


  2. 的#pragma 一旦不能在这个特殊的编译工作,因此如何解决?
    有人贴出<一个href=\"http://stackoverflow.com/questions/223771/repeated-multiple-definition-errors-from-including-same-header-in-multiple-cpps#223798\">this回答类似的问题。它似乎并没有为我工作。这是如何解决的?



解决方案

如果连接器是抱怨,这意味着你必须定义,而不是仅仅在声明你的头。这里的东西,将是错误的例子。

 的#ifndef X_H
#定义X_HINT myFunc的()
{
  返回42; //错!定义标题。
}INT myVar的; //错!定义标题。#万一

您应该分成源文件和头文件是这样的:

标题:

 的#ifndef X_H
#定义X_HEXTERN INT myFunc的();EXTERN INT myVar的;#万一

c来源:

  INT myFunc的()
{
  返回42;
}INT myVar的;

I have a header file x.h which is included by more than one *.c source files. This header file has some structure variables defined.

I have put multiple inclusion prevention guard at the beginning of the header file as:

#ifndef X_H
#define X_H
...
..
//header file declarations and definitons.


#endif//X_H

On building I get linker errors related to multiple definitions. I understand the problem.

  1. Won't a multiple inclusion prevention guard at the top of header file as I have, prevent multiple inclusions of the header file x.h and thereby avoid multiple definitions of the variables that are there in x.h?

  2. #pragma once does not work on this particular compiler, so what is the solution? Someone had posted this answer to a similar question. It doesn't seem to work for me. How does this solution work?

解决方案

If the linker is complaining, it means you have definitions rather than just declarations in your header. Here's an example of things that would be wrong.

#ifndef X_H
#define X_H

int myFunc()
{
  return 42; // Wrong! definition in header.
}

int myVar; // Wrong! definition in header.

#endif

You should split this into source and header file like this:

Header:

#ifndef X_H
#define X_H

extern int myFunc();

extern int myVar; 

#endif

C Source:

int myFunc()
{
  return 42; 
}

int myVar;

这篇关于为什么我的编译警卫preventing多重定义的夹杂物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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