2011-12-14 59 views
0

我一直在试图编译一个多文件项目,但每次我尝试在player.cpp中使用void时,我都会收到此错误消息,在编译过程中创建的player.o具有void player_action(...)的相同定义。当我尝试在其他文件中使用void时,会出现相同的问题,并带有相应的.o文件。但是,如果我在任何文件中使用结构体,则不会发生任何问题,并且不会发生“多重定义”错误。下面的代码是编译器给我的错误信息。编译打嗝在C++和.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()的额外定义。

+1

这是什么意思“使用void”? – 2011-12-14 01:56:44

+0

它意味着使用这样的东西:void player_action(int x,int y){...}。 – Ripspace 2011-12-14 01:58:24

回答

2

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

0

如果你需要从你的程序的几个部分访问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的'The C++ programming language'