多个定义和仅标头库 [英] Multiple definition and header-only libraries

查看:118
本文介绍了多个定义和仅标头库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有几个c和h文件的C程序。我决定将程序的一部分设置为仅限标题,因此我将代码从c移到了h。现在我得到了多重定义问题,我不明白为什么。例如:

I have a C program with several c and h files. I decided to make one part of the program 'header-only' so I moved the code from c to h. Now I'm getting multiples definition problems and I have no idea why. e.g.:

main.c includes utils.h
vector.c includes utils.h

我将utils.c中的所有内容移动到utils.h(当然还从项目中删除了utils.c)。 utils.h以

I moved everything in utils.c to utils.h (and of course removed utils.c from the project). utils.h starts with

#ifndef UTILS_H_
#define UTILS_H_

// and end with:
#endif

为了确保我的警卫是独一无二的,我试着改变它(例如:UTILS718171_H_)但它不起作用。

To be sure my guard was unique I tried changing it (e.g.: UTILS718171_H_) but it doesn't work.

仍然,编译器抱怨:

/tmp/ccOE6i1l.o: In function `compare_int':
ivector.c:(.text+0x0): multiple definition of `compare_int'
/tmp/ccwjCVGi.o:main.c:(.text+0x660): first defined here
/tmp/ccOE6i1l.o: In function `compare_int2':
ivector.c:(.text+0x20): multiple definition of `compare_int2'
/tmp/ccwjCVGi.o:main.c:(.text+0x6e0): first defined here
/tmp/ccOE6i1l.o: In function `matrix_alloc':
ivector.c:(.text+0x40): multiple definition of `matrix_alloc'
/tmp/ccwjCVGi.o:main.c:(.text+0x0): first defined here
...

问题可能是这样的:所有c文件都已编译并获得自己的版本代码的离子,然后在连接它导致问题,但我真的不知道如何解决这个问题。

The problem might be something like: all c files are compiled and get their own version of the code and then at linkage it causes problem, but I have honestly no idea how to solve this problem.

推荐答案

如果你在头文件中定义你的变量并在多个c文件中包含标题,你必须得到多个定义错误,因为你打破了一个定义规则(ODR),它指出应该只有一个翻译单元中的一个定义(标题文件+源文件)。

If you define your variables inside your header file and include the header in several c files, you are bound to get multiple definitions error because you break the One definition rule(ODR), which states that there should be only one definition in one Translation Unit(header files + source file).

解决方案是:

你应该定义你得到的实体多次定义错误。

For Functions:

在头文件中声明函数原型(你包含在其他源文件中)并在一个且只有一个源文件中定义函数。

对于全局变量:

在头文件中声明变量extern(包含在其他源文件中)然后定义th 一个且只有一个源文件中的变量。

Solution is:
You should define the entities you get Multiple definition errors for only once.
For Functions:
Declare the function prototypes in header file(which you include in other source files) and define the function in one and only one source file.
For Global variables:
You declare the variable extern in header file(which you include in other source files) and then define the variable in one and only one source file.

这篇关于多个定义和仅标头库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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