为什么我的编译防护不能防止多个定义包含? [英] Why aren't my compile guards preventing multiple definition inclusions?

查看:16
本文介绍了为什么我的编译防护不能防止多个定义包含?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个头文件 x.h,它包含在多个 *.c 源文件中.这个头文件定义了一些结构变量.

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. 不会像我一样在头文件顶部设置多重包含防护,防止头文件 xh 的多重包含,从而避免 xh 中存在的变量的多重定义吗?

  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?

#pragma once 在这个特定的编译器上不起作用,那么解决方案是什么?有人发布了 这个回答一个类似的问题.它似乎对我不起作用.这个解决方案是如何工作的?

#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:

标题:

#ifndef X_H
#define X_H

extern int myFunc();

extern int myVar; 

#endif

C 来源:

int myFunc()
{
  return 42; 
}

int myVar; 

这篇关于为什么我的编译防护不能防止多个定义包含?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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