共享C数组的最优雅的方式

共享C数组的最优雅的方式

本文介绍了共享C数组的最优雅的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个源模块,其中包含一个源模块很多时候,我们称之为 utilities.h utilities.c
其中,我有一个重要的数组,我们称之为

  #define IMPORTANT_ARRAY_LENGTH 10000 
char important_array [IMPORTANT_ARRAY_LENGTH];

这个实用程序中有很多其他函数模块,并且它们都工作正常。但是,在其他源文件之一中,我们称之为 worker.c ,我必须使用这个数组。什么是官方,优雅的方式来做到这一点,而不必在 worker中放置 extern char important_array [IMPORTANT_ARRAY_LENGTH] 和宏定义。 c



如果我执行以下操作:

utilities.h p>

  #ifndef _UTILITIES_H_ 
#define _UTILITIES_H_

#define IMPORTANT_ARRAY_LENGTH 10000
extern char important_array [IMPORTANT_ARRAY_LENGTH];

// ...

utilities.c

  #ifndef _UTILITIES_C_ 
#define _UTILITIES_C_

#includeutilities.h

char important_array [IMPORTANT_ARRAY_LENGTH];

// ...

worker.c

  #includeutilities.h
// ...
important_array [0] = 0;

那么我的数组将是 worker.c 。如果我在 utilities.h 中不使用 extern 关键字,那么它当然是一个重复的符号。 (奇怪的是,它只编译了一个警告,我可以从链接文件中看到大小被分配了多次。)

我真的必须声明我的数组在 worker.c 中?我想保持一切都干净,并且只将所有声明放在一个地方:在一个头文件中。我希望只有一次宏定义(这是次要的,因为我可以使用const,但我希望预处理器能够处理它,而不是占据位置)。

解决方案

你拥有的是规范的方法:在头文件中有一个 extern 声明,并在 .c 文件。

不,它不会。你的代码会编译并链接就好。


I have to turn back to (embedded) C after some lengthy time with C++, and have the following problem:

I have a source module which is included a lot of times, let's call it utilities.h and utilities.cIn it, I have an important array, let's call it

#define IMPORTANT_ARRAY_LENGTH  10000
char important_array[IMPORTANT_ARRAY_LENGTH];

I have a lot of other functions in this utilities module, and they all work fine. However, in one of the other source files, let's call it worker.c, I have to use this array. What is the "official", elegant way to do this, without having to put extern char important_array[IMPORTANT_ARRAY_LENGTH] and the macro definition in the worker.c ?

If I do the following:

utilities.h

#ifndef _UTILITIES_H_
#define _UTILITIES_H_

#define IMPORTANT_ARRAY_LENGTH  10000
extern char important_array[IMPORTANT_ARRAY_LENGTH];

// ...

utilities.c

#ifndef _UTILITIES_C_
#define _UTILITIES_C_

#include "utilities.h"

char important_array[IMPORTANT_ARRAY_LENGTH];

// ...

worker.c

#include "utilities.h"
// ...
important_array[0] = 0;

then my array will be an undefined symbol in worker.c. If I don't use the extern keyword in utilities.h, then of course, it's a duplicate symbol. (Strangely, it compiles with just a warning, and I can see from the linker file that the size is allocated multiple times.)

Do I really have to declare my array in worker.c? I want to keep everything clean, and have all declarations in one place only: in a header file. And I want to have the macro definition only once (this is secondary, because I could use a const, but I want the preprocessor to handle it, and not take up place)

解决方案

What you have is the canonical way to do it: have an extern declaration in the header file, and define the variable in the .c file.

No, it won't. Your code will compile and link just fine.

这篇关于共享C数组的最优雅的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 18:06