C++ 中可以使用全局数组吗?破坏二进制兼容性?
假设一个共享库包含以下几行:
const char* const arr[] =
{
"one",
"two",
"three"
};
1) 应用程序可以链接到该库并使用符号“arr”吗?
2)如果定义中添加新元素,二进制兼容性是否会被破坏?
3)如果其中一个字符串文字发生变化怎么办?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
1) 是
2) 否
3) 不是问题
4) 你为什么不这么认为?
1) Yes
2) No
3) Not a problem
4) Why would you think otherwise?
在任何情况下都不会破坏二进制兼容性。
C 样式数组不会存储数组的长度或对其进行假设,因此增加数组的长度不会破坏任何假设。
您有一个指针数组,因此更改字符串文字根本不会影响数组的内存布局。
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.
无论数组中有哪些元素,符号 arr 都指向数组的基址。您可以更改元素数量或一个或多个元素的值,并且 arr 符号仍然指向数组的开头。
但是,应用程序可能需要有关 arr 的更多信息:它可能想知道它有多少个元素。
使用 NULL 指针终止列表,或导出大小:
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:
1) 是的,前提是它声明了
extern
(请注意,const
对象默认具有静态链接;是的,这是违反直觉的;))。2) 取决于链接到它的代码如何使用该 arr。如果您希望新条目对外部代码有用,则
arr
应该以 NULL 结尾,或者应附带extern const unsigned arr_size = sizeof(arr) / sizeof(arr[0])
.3) 没关系。数组本身由指向文字表示的指针组成;如果文字发生变化,数组本身的布局不会改变。
4) 不,因为
arr
是指向文字表示的指针的连续序列,仅此而已。1) Yes, provided that it declared
extern
(note thatconst
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 anextern 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.