我想知道如何区分声明和定义。我读了一些与这个主题相关的问题,但现在我只能在基本功能中做到这一点。问题是当我尝试在头文件中声明常量全局变量时,我想在函数中使用这个常量,该函数在同一位置声明但在其他文件中定义。我有 2 个扩展名为 .c 的文件和一个扩展名为 .h 的文件。
文件main_lib.h包含:
#ifndef _MAIN_LIB_H_
#define _MAIN_LIB_H_
const int N_POINTS=10;
struct Point{
int x;
int y;
};
void fill_random(struct Point points[], int n);
void closest(struct Point points[], int n, struct Point* p);
#endif /* _MAIN_LIB_H_ */
文件main_lib.c包含:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "main_lib.h"
void fill_random(struct Point points[], int n){
...
}
void closest(struct Point points[], int n, struct Point* p){
...
}
最后一个名为 main.c 的文件包含:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "main_lib.h"
int main()
{
srand(time(0));
struct Point random_points[N_POINTS];
struct Point *p;
p=&random_points[0];
fill_random(p,N_POINTS);
closest(p,N_POINTS,p);
return 0;
}
问题是如何更正此代码以在没有错误状态的情况下运行它。非常感谢您的帮助。
最佳答案
The problem is when I try to declare constant global variable in header file ...
how to correct this code to run it without error status(?)
相反,在 main_lib.h 中声明 extern
@Scheff .如果全局变量是非 const
或 volatile
,这将是相同的。
// const int N_POINTS=10;
extern const int N_POINTS;
只在 main_lib.c 中定义一次
// add
const int N_POINTS=10;
关于c - 其他C文件中声明和定义的划分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48187398/