using sizeof() on externs

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 
已解决

using sizeof() on externs

跳至解决方案
3,023 次查看
irob
Contributor V
Hey guys, here's my setup:

Code:
main.c
#include "main.h"
const Byte array1[] = "sample string";

main.h
#define ARRAY_SIZE sizeof(array1)

file2.c
#include "main.h"
extern const Byte array1[];

for (i=0; i<ARRAY_SIZE; i++)
{
  Function(array1[i]);
}

What I'm getting with this is a C1838 error: Unknown object-size: sizeof (incomplete type).

Yet, if I simply move that array declaration from main.c into file2.c where the array is used, all will compile.  The trouble is, I really need the array with the string to be located inside main.c.

Any ideas what I'm doing wrong?  It's got to be with my extern, right?
标签 (1)
标记 (1)
0 项奖励
1 解答
1,035 次查看
irob
Contributor V
Thanks, Guru.  Assigning another variable the value of the size and then using that variable later worked fine.

在原帖中查看解决方案

0 项奖励
4 回复数
1,035 次查看
CompilerGuru
NXP Employee
NXP Employee
That's how the C language is works, the compiler just does not know the size when only the declaration without size is known.

As possible solutions you could:
- specify the array size in the declaration:
main.h:

extern const Byte array1[14];

The disadvantage is obviously that you have to maintain the array
size explicitly. The compiler will check the size at least when he
sees the declaration and the definition while compiling main.c
(say when the extern declaration is in main.h)

-define another constant with the size.
main.h:
extern const Byte array1[];
extern const size_t array1_size;
#define ARRAY_SIZE array1_size
main.c:
#include "main.h"
const Byte array1[] = "Sample";
const size_t array1_size = sizeof(array1);

The disadvantage here is that the code is a little bit less efficient
as the array size is no longer known at compile time, but has to be
actually read from a constant at runtime instead.

Daniel



1,035 次查看
Lundin
Senior Contributor IV
To simply hardcode the array size seems to be the best solution to me. There is no such thing as "dynamic array length" in an embedded system, and there shouldn't be either. There is always a maximum length: the number of symbols available on the LCD etc.

Though, in this particular case, this would be another acceptable solution:

unsigned char a_size = strlen(array1);

for (i=0; i a_size; i++)
{
Function(array1[i]);
}
0 项奖励
1,035 次查看
irob
Contributor V
Lundin, you're absolutely right.  In this case, my string is for storing the firmware version number.  For me, this can be from 3 characters ("1.0") up to 5 ("1.2.3").  Since that varies for me, I'd rather leave open the option to put as many characters I need.  And since I'm the sole maintainer of this firmware, I can make sure that it's in an available flash range.
0 项奖励
1,036 次查看
irob
Contributor V
Thanks, Guru.  Assigning another variable the value of the size and then using that variable later worked fine.
0 项奖励