c - 其他C文件中声明和定义的划分

标签 c constants declaration definition

我想知道如何区分声明和定义。我读了一些与这个主题相关的问题,但现在我只能在基本功能中做到这一点。问题是当我尝试在头文件中声明常量全局变量时,我想在函数中使用这个常量,该函数在同一位置声明但在其他文件中定义。我有 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 .如果全局变量是非 constvolatile,这将是相同的。

// 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/

相关文章:

c - PostgreSQL 中的聚合函数将数组传递给 C 函数

c++ - 在表达式模板中需要非常量表达式类

C++11:字符串文字的类型是 "array of the appropriate number of const characters"

javascript - 为什么函数在构造函数中声明时不使用 new 关键字?

c - 在多线程应用程序中,如何根据线程在单独的文件中重定向 stderr 和 stdout?

c - 获取要调用的正确 Lua 元方法 (C-api)

rust - 如何在 const 结构中初始化 BTreeMap?

javascript - 你可以在 Javascript 中创建一个对象而不声明每个值吗?如何?

c++ - 声明一个没有长度的静态数组,然后定义一个长度是否有效?

c - 如何通过选择 c 中的行和列来查找二维数组的子集?