“多个定义”,“首先在此定义”和“多个定义”。错误 [英] "Multiple definition", "first defined here" errors

查看:233
本文介绍了“多个定义”,“首先在此定义”和“多个定义”。错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个项目:服务器客户端 Commons 。制作标题& Commons 中的源对不会导致任何问题,我可以从服务器客户端中自由访问这些函数。

I have 3 projects: Server, Client and Commons. Making header & source pairs in Commons doesn't cause any problems and I can access the functions freely from both Server and Client.

但是,出于某种原因,在 Server Client 项目中创建其他源/头文件总是会导致多个定义(...)首先在这里定义错误。

However, for some reason making additional source/header files within Server or Client project always causes multiple definition of (...) and first defined here errors.

示例:

commands.h (在客户端项目的根目录中)

commands.h (in root dir of the Client project)

#ifndef COMMANDS_H_
#define COMMANDS_H_

#include "commands.c"

void f123();

#endif /* COMMANDS_H_ */

commands.c (在客户端项目的根目录中)

commands.c (in root dir of the Client project)

void f123(){

}

main.c (在root中) 客户项目的目录)

main.c (in root dir of the Client project)

#include "commands.h"
int main(int argc, char** argv){

}

错误:

make: *** [Client] Error 1      Client
first defined here              Client
multiple definition of `f123'   commands.c

清理,重建索引,重建项目没有帮助。也没有重新启动计算机。

Cleaning, rebuilding index, rebuilding projects doesn't help. Neither does restarting the computer.

推荐答案

这里的问题是你包括 commands.c in commands.h 。因此,C预处理器在函数原型之前将 commands.c 的内容插入 commands.h commands.c 包含函数定义。因此,函数定义在导致错误的函数声明之前结束。

The problem here is that you are including commands.c in commands.h before the function prototype. Therefore, the C pre-processor inserts the content of commands.c into commands.h before the function prototype. commands.c contains the function definition. As a result, the function definition ends up before than the function declaration causing the error.

commands.h的内容在预处理器阶段之后如下所示:

The content of commands.h after the pre-processor phase looks like this:

#ifndef COMMANDS_H_
#define COMMANDS_H_

// function definition
void f123(){

}

// function declaration
void f123();

#endif /* COMMANDS_H_ */

这是一个错误,因为你不能在C中定义后声明一个函数。如果你交换 #includecommands.c和函数声明错误不应该发生因为,现在,函数原型出现在函数声明之前。

This is an error because you can't declare a function after its definition in C. If you swapped #include "commands.c" and the function declaration the error shouldn't happen because, now, the function prototype comes before the function declaration.

但是,包含 .c 文件是不良做法,应该避免。解决此问题的更好方法是在 commands.c 中包含 commands.h 并链接编译后的命令版本到主文件。例如:

However, including a .c file is a bad practice and should be avoided. A better solution for this problem would be to include commands.h in commands.c and link the compiled version of command to the main file. For example:

commands.h

ifndef COMMANDS_H_
#define COMMANDS_H_

void f123(); // function declaration

#endif

commands.c

#include "commands.h"

void f123(){} // function definition

这篇关于“多个定义”,“首先在此定义”和“多个定义”。错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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