views:

109

answers:

4

Say a shared library contains the following lines:

const char* const arr[] =
{
  "one",
  "two",
  "three"
};

1) Can an application link to this library and use the symbol "arr"?

2) Is binary compatibility broken if a new element is added to the definition?

3) How about if one of the string literals is changed?

4) Why (not)?

Cheers, Luke

+4  A: 

1) Yes

2) No

3) Not a problem

4) Why would you think otherwise?

anon
Your answer is largely correct, but missing a subtle detail I pointed out in comments on the question.
Omnifarious
+4  A: 

Binary compatibility is not broken in either case.

C-style arrays do not store or make assumptions on an array's length, so increasing the length of the array will not break any assumptions.

You have an array of pointers, so changing a string literal will not affect the memory layout of your array at all.

Shmoopty
+2  A: 

The symbol arr points to the base of the array regardless of what elements are in the array. You can change the number of elements or the value of one or more elements and the arr symbol still points to the start of the array.

The application might need some more information about arr, however: It probably wants to know how many elements it has.

Either terminate the list with a NULL pointer, or export the size:

const size_t arrSize = sizeof(arr)/sizeof(char*);
Richard Pennington
+1 for remembering to publish the size of the array.
Thomas Matthews
+2  A: 

1) Yes, provided that it declared extern (note that const objects have static linkage by default; yes, it's counter-intuitive ;) ).

2) Depends on how this arr is used by the code that links to it. If you'd like new entries to be useful to the external code, either arr should be NULL-terminated, or it should be accompanied with an extern const unsigned arr_size = sizeof(arr) / sizeof(arr[0]).

3) That's fine. The array itself consists of pointers to literals representation; if a literal changes, layout of array itself won't change.

4) No, because arr is a contiguous sequence of pointers to literals representations, that's all.

atzz
+1 for mentioning that const objects have static linkage. (For completeness: this applies to C++ only, in C const does not affect linkage.)
avakar