dun*_*ski 5 c arrays linker compilation
我想共享sizeof(array)两个 .c 模块之间的值。该数组在文件 A 中初始化,因此编译器在编译时知道大小,然后我想在另一个 B 文件中使用该数组的大小。
示例:
在 Ac 文件中:
int arr[] = {1, 2, 3};
.
.
.
for (int i = 0; i < sizeof(arr); i++); // that works
Run Code Online (Sandbox Code Playgroud)
在 Ah 文件中:
extern int arr[];
Run Code Online (Sandbox Code Playgroud)
在 Bc 文件中:
#include "A.h"
.
.
.
for (int i = 0; i < sizeof(arr); i++); // here compiler doesn't know size of this arr
Run Code Online (Sandbox Code Playgroud)
有没有办法使这项工作?我知道为什么这不起作用,但也许有一个偷偷摸摸的技巧来解决这个问题。
有办法让这项工作发挥作用吗?我知道为什么这不起作用,但也许有一个偷偷摸摸的技巧可以解决这个问题。
这不是很偷偷摸摸,但它确实有效......
在some.h
//declare as extern for project global scope
extern int arr[];
extern size_t gSizeArray;
Run Code Online (Sandbox Code Playgroud)
然后在some.c
//define and initialize extern variables in 1 (and only one) .c file,
int arr[] = { 1,2,3 };
size_t gSizeArray = sizeof(arr)/sizeof(arr[0]);
Run Code Online (Sandbox Code Playgroud)
其中someother.c包括some.h
#include "some.h"
//you can now see the value of gSizeArray in this file
printf("%zu\n%d,%d,%d\n", gSizeArray, arr[0], arr[1], arr[2]);//should output
Run Code Online (Sandbox Code Playgroud)
3
1,2,3
警告
以这种方式使用 extern 的
价值在于该变量的值可以在一个模块中更改,并且可以在包含以下内容.c的任何文件中看到相同的值 some.h
推论以这种方式使用 extern的问题
是该变量的值可以在一个模块中更改,并且可以在包含..c some.h
(或者换句话说,要小心。全局变量,特别是extern全局变量可能会有所帮助,但它们也可能很危险。特别是对于不是代码作者的代码维护者来说,他们可能不知道变量是extern范围,并在不知不觉中以不适当的方式使用它。
顺便说一句,在这篇文章中,关于使用extern作用域的内容可能比您想了解的还要多。