Предварительные определения в C и соединении

Необходимо использовать пакет iconv , конкретно его функция iconv.

32
задан Antti Haapala 28 March 2019 в 19:33
поделиться

3 ответа

See also What are extern variables in C. This is mentioned in the C standard in informative Annex J as a common extension:

J.5.11 Multiple external definitions

There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2).

Warning

As @litb points out here, and as stated in my answer to the cross-referenced question, using multiple definitions for a global variable leads to undefined behaviour, which is the standard's way of saying "anything could happen". One of the things that can happen is that the program behaves as you expect; and J.5.11 says, approximately, "you might be lucky more often than you deserve". But a program that relies on multiple definitions of an extern variable - with or without the explicit 'extern' keyword - is not a strictly conforming program and not guaranteed to work everywhere. Equivalently: it contains a bug which may or may not show itself.

28
ответ дан 27 November 2019 в 21:01
поделиться

Существует так называемое «общее расширение» стандарта, в котором разрешено многократное определение переменных при условии, что переменная инициализируется только один раз. См. http://c-faq.com/decl/decldef.html

На связанной странице говорится, что это относится к платформам Unix - я думаю, для c99 это то же самое, что и для c89 - хотя, возможно, это было принят большинством компиляторов, чтобы сформировать своего рода стандарт де-факто. Интересно.

9
ответ дан 27 November 2019 в 21:01
поделиться

Это проясняет мой ответ на комментарий olovb:

вывод nm для объектного файла, скомпилированного из "int x;". На этой платформе к символам добавляется '_', то есть переменная x отображается как _x.

00000000 T _main
         U _unknown
00000004 C _x
         U dyld_stub_binding_helper

вывод nm для объектного файла, скомпилированного из "int x = 1;"

00000000 T _main
         U _unknown
000000a0 D _x
         U dyld_stub_binding_helper

вывод nm для объектный файл, скомпилированный из "int x = 0;"

00000000 T _main
         U _unknown
000000a0 D _x
         U dyld_stub_binding_helper

вывод nm для объектного файла, скомпилированного из "extern int x;"

00000000 T _main
         U _unknown
         U dyld_stub_binding_helper

EDIT: вывод nm для объектного файла, скомпилированного из "extern int x;" где x фактически используется в одной из функций

00000000 T _main
         U _unknown
         U _x
         U dyld_stub_binding_helper
7
ответ дан 27 November 2019 в 21:01
поделиться
Другие вопросы по тегам:

Похожие вопросы: