【问题标题】:Compiler Hiccup in C++ and with .o FilesC++ 中的编译器 Hiccup 和 .o 文件
【发布时间】:2011-12-14 01:51:58
【问题描述】:

我一直在尝试编译一个多文件项目,但是每次我尝试在 player.cpp 中使用 void 时,我都会不断收到此错误消息,似乎是在编译期间创建的 player.o void player_action(...) 的定义相同。当我尝试在其他文件中使用 void 时,会出现同样的问题,它们对应的 .o 文件。但是,如果我在任何文件中使用结构,都不会出现问题,也不会出现“多重定义”错误。下面几行是编译器给我的错误信息。

obj\Debug\player.o: In function `Z13player_actioniii':
D:/Projects/Blackmail Mailman/player.cpp:13: multiple definition of `player_action(int, int, int)'
obj\Debug\main.o:D:/Projects/Blackmail Mailman/player.cpp:13: first defined here

这是我使用的 player.cpp 中的代码:

#include "include_files.cpp"

struct player_struct
{
    int x;
    int y;
int previous_x;
int previous_y;
    int mode;
};

void player_action(int x, int y, int mode)
{
    SDL_Event event;
    if (SDL_PollEvent(&event))
    {
    if (event.type == SDL_KEYDOWN)
    {
        switch(event.key.keysym.sym)
        {
            case SDLK_RIGHT:;
        };
    };
    };
};

可能出了什么问题,我该如何解决?我在 Mingw 和 Windows XP 中使用 Codeblocks。我已经检查了其他文件,没有任何额外的 void player_action() 定义。

【问题讨论】:

  • “使用空白”是什么意思?
  • 意思是这样使用:void player_action(int x, int y){...}。
  • 您可能多次包含包含函数定义的文件。没有源代码很难说。
  • 您需要发布代码以获得帮助。
  • 你为什么#includeing .cpp 文件?这可能是奇怪的原因。

标签: c++ compiler-errors codeblocks


【解决方案1】:

你永远不会#include .cpp 文件,而只有 .h 文件。

【讨论】:

  • 如果您这样做 #include .cpp 文件,您将在多个翻译单元中编译相同的代码,从而赋予事物多个定义。
  • 那么,如何“包含”c++ 文件?如果不能,哪里有关于 .h 文件的好教程?
  • @Ripspace 尝试简单的#include "include_files.h" 而不是你所拥有的。 (编辑:或者任何对应的 .h 文件是 include_files.cpp。)
  • @Ripspace,很高兴为您提供帮助。甚至无法计算我在一天中看到的所有“多重定义”错误。
【解决方案2】:

如果您需要从程序的多个部分访问void player_action(),您应该创建一个头文件myapi.h,其中包含以下内容:

//myapi.h
#ifndef MYAPI_HEADER 
#define MYAPI_HEADER

void player_action(int x, int y, int mode);

/* more function declarations */

#endif

定义函数的文件是这样的:

//player.cpp

#include "myapi.h"

void player_action(int x, int y, int mode)
{
 /*...*/
}

使用它的文件会是这样的:

//main.cpp
#include "myapi.h"

void GameCycle()
{
 /*...*/
 player_action(0,0,0);
 /*...*/
 }

切勿使用#include 包含对象定义,除非您知道自己在做什么。即使你知道,你也应该三思而后行。始终使用包含保护 (#ifndef ... #define .. #endif) - 这将防止多次包含您的标头。

这些是基本建议。我在 B. Stroustrup 的“C++ 编程语言”中看到了对这些东西的一个很好的解释

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    相关资源
    最近更新 更多