【发布时间】:2018-12-22 15:37:39
【问题描述】:
在我的 CLion 项目中,我有一些标题。其中之一是constants.h,我将所有常量都放入其中。现在,我想在main.c 和view.h 中使用这个标头。 view.c 是另一个与view.h 关联的源文件。每当我使用它时,它都会因为重新定义常量而出错。我也用过:
//constants.h
#ifndef PROJECT_CONSTANTS_H
#define PROJECT_CONSTANTS_H
# define pi 3.14159265359
# define degToRad (2.000*pi)/180.000
//GAME GRAPHICS CONSTANTS
const int TANK_RADIUS = 15;
const int CANNON_LENGTH = TANK_RADIUS;
const int BULLET_RADIUS = 4;
const int BULLET_SPAWN_POS = TANK_RADIUS+BULLET_RADIUS;
//const int tank_width = 10;
//const int tank_height = 20;
const int WIDTH = 800;
const int HEIGHT = 600;
//GAME LOGICAL CONSTANTS
const int step = 5;
const double angleStep = 4.5;
const int bulletSpeed = 8;
#define maxBulletPerTank 10
#endif
//main.c includes
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <SDL.h>
#include <SDL2_gfxPrimitives.h>
#include "structs.h"
#include "view.h"
//view.h
#ifndef PROJECT_VIEW_H
#define PROJECT_VIEW_H
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <SDL.h>
#include <SDL2_gfxPrimitives.h>
#include "constants.h"
SDL_Renderer* init_windows(int width , int height);
#endif
//view.c
#include "view.h"
SDL_Renderer* init_windows(int width , int height)
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("workshop", 100, 120, width, height, SDL_WINDOW_OPENGL);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
return renderer;
}
在 constants.h 的第一部分,但在 main.c 和 view.h 中都包含它会给我错误。有没有办法解决这个问题?请注意,如果我没有将它包含在 view.h 中,它就无法识别某些使用constants.h 中定义的常量的部分。我需要在其他几个.h 文件中使用这个常量。
在main.c 和view.h 的顶部我有:#include<constants.h> 并且我在view.c 的顶部有#include<view.h>。 view.h也包含在main.c的顶部
其中一个错误:
CMakeFiles\project_name.dir/objects.a(view.c.obj):[address]/constants.h:26: multiple definition of `step':
CMakeFiles\project_name.dir/objects.a(main.c.obj):[address]/constants.h:23: first defined here
我是标准编程的新手,不知道如何处理。
【问题讨论】:
-
您能告诉我们您的错误信息吗?
-
@NaWeeD 我添加了 constants.h 代码和其中一个错误。
-
constants.h本身看起来还不错,并且具有正确的#ifndef/#define样板可以工作。view.h中的#ifndef/#define设置是否也相同?文件如何相互导入? -
step是否在view.c的其他地方声明?如果问题出在整个包含中,则错误应该是关于TANK_RADIUS,这是其中的第一个定义,而不是step。它只对step失败的事实引发了问题。
标签: c header-files