быдлокодер
 Аватар для kravam
1724 / 911 / 106
Регистрация: 04.06.2008
Сообщений: 5,697

Опция -shared компилятора g++, где она прописана?

02.04.2013, 15:24. Показов 3101. Ответов 7
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
То есть ситуация: я кропаю dll (создадим пустой файл test.cpp, он демонстрационный, единственную необходимую функцию при отсутсвии оной линкёр вставит сам.) Сдуем откуда-нибудь из гугла пример командной строки:

Bash
1
g++ -shared -o test.dll test.cpp
И попробуем разобраться с параметрами. Командуем:
Bash
1
g++ --h
Наблюдаем:

тут вывод по команде g++ --h
Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
Usage: g++ [options] file...
Options:
  -pass-exit-codes         Exit with highest error code from a phase
  --help                   Display this information
  --target-help            Display target specific command line options
  --help={target|optimizers|warnings|params|[^]{joined|separate|undocumented}}[
,...]
                           Display specific types of command line options
  (Use '-v --help' to display command line options of sub-processes)
  --version                Display compiler version information
  -dumpspecs               Display all of the built in spec strings
  -dumpversion             Display the version of the compiler
  -dumpmachine             Display the compiler's target processor
  -print-search-dirs       Display the directories in the compiler's search pat
h
  -print-libgcc-file-name  Display the name of the compiler's companion library
 
  -print-file-name=<lib>   Display the full path to library <lib>
  -print-prog-name=<prog>  Display the full path to compiler component <prog>
  -print-multi-directory   Display the root directory for versions of libgcc
  -print-multi-lib         Display the mapping between command line options and
 
                           multiple library search directories
  -print-multi-os-directory Display the relative path to OS libraries
  -print-sysroot           Display the target libraries directory
  -print-sysroot-headers-suffix Display the sysroot suffix used to find headers
 
  -Wa,<options>            Pass comma-separated <options> on to the assembler
  -Wp,<options>            Pass comma-separated <options> on to the preprocesso
r
  -Wl,<options>            Pass comma-separated <options> on to the linker
  -Xassembler <arg>        Pass <arg> on to the assembler
  -Xpreprocessor <arg>     Pass <arg> on to the preprocessor
  -Xlinker <arg>           Pass <arg> on to the linker
  -save-temps              Do not delete intermediate files
  -save-temps=<arg>        Do not delete intermediate files
  -no-canonical-prefixes   Do not canonicalize paths when building relative
                           prefixes to other gcc components
  -pipe                    Use pipes rather than intermediate files
  -time                    Time the execution of each subprocess
  -specs=<file>            Override built-in specs with the contents of <file>
  -std=<standard>          Assume that the input sources are for <standard>
  --sysroot=<directory>    Use <directory> as the root directory for headers
                           and libraries
  -B <directory>           Add <directory> to the compiler's search paths
  -v                       Display the programs invoked by the compiler
  -###                     Like -v but options quoted and commands not executed
 
  -E                       Preprocess only; do not compile, assemble or link
  -S                       Compile only; do not assemble or link
  -c                       Compile and assemble, but do not link
  -o <file>                Place the output into <file>
  -x <language>            Specify the language of the following input files
                           Permissible languages include: c c++ assembler none
                           'none' means revert to the default behavior of
                           guessing the language based on the file's extension
 
Options starting with -g, -f, -m, -O, -W, or --param are automatically
 passed on to the various sub-processes invoked by g++.  In order to pass
 other options on to these processes the -W<letter> options must be used.
 
For bug reporting instructions, please see:
<http://gcc.gnu.org/bugs.html>.
 
 
 
Так, вот как надо использовать:
g++ [options] file...

В нашем варианте "-shared" и "-o test.dll" это опции. Если с "-o test.dll" всё понятно (о ней вывелась инфа), то необходимость "-shared" ставит в тупик, про "-shared" вобще нигде ничё нет. Тем не менее, она необходима. Без неё получается ругань (компилятор предполагает, что мы кропаем *.exe и не может найти main)

То, что опция "-shared" передаётся подпроцессам- тоже сомнения в этом. Ибо в документации написано, как надо передавать опции подпроцессам, используя:
-g, -f, -m, -O, -W, or --param
В общем, хотелось бы применять опцию -shared зная, что делаю, а не потому, что компилится. Где о ней написано в help? Спасибо, кто откликнется.

g++ 4.6.2
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
02.04.2013, 15:24
Ответы с готовыми решениями:

Неизвестная опция компилятора '-Wl'
ОС Windows XP SP3. Установил mingw. Скачал Qt-4.4.0 и Qwt-6.0.1. В консоле Qt-4.4.0 выполняю: qmake qwt.pro mingw32-make ...

Внутри переменной прописана капча. На странице она не отображается
Всем привет. Такой вопрос. У меня внутри переменнной пхп прописана капча. На странице она не отображается. Есть предположение что проблема...

Не работает опция -sourcepath компилятора javac
Эта опция, как я понимаю, должна указывать компилятору путь, где искать *.java- сырцы &gt;javac Usage: javac &lt;options&gt;...

7
Псевдослучайный
1946 / 1146 / 98
Регистрация: 13.09.2011
Сообщений: 3,215
02.04.2013, 16:49
Это опция линкера, а не компилятора, соответственно, и man/help надо смотреть к нему.
0
быдлокодер
 Аватар для kravam
1724 / 911 / 106
Регистрация: 04.06.2008
Сообщений: 5,697
02.04.2013, 16:56  [ТС]
Ну так если это опция линкёра, он является ведь подпроцессом для g++, следовательно, ему надо передавать опцию -shared должным образом. Вот так например:
Bash
1
-Wl,--shared
Это правильная передеча, согласно help. Но она не работает почему-то. А способ который я использую он работает, но не оговорён в части передачи параметров линкёру, почему?
0
Псевдослучайный
1946 / 1146 / 98
Регистрация: 13.09.2011
Сообщений: 3,215
02.04.2013, 17:03
Он оговорён. Но в мане, а не в хелпе, который нужен для _краткого_ описания команды.
Цитата Сообщение от man g++
Options for Linking
These options come into play when the compiler links object files into an executable
output file. They are meaningless if the compiler is not doing a link step.

....

-shared
Produce a shared object which can then be linked with other objects to form an
executable. Not all systems support this option. For predictable results, you must
also specify the same set of options that were used to generate code (-fpic, -fPIC, or
model suboptions) when you specify this option.
0
быдлокодер
 Аватар для kravam
1724 / 911 / 106
Регистрация: 04.06.2008
Сообщений: 5,697
02.04.2013, 17:05  [ТС]
Не пойдёт. Мне нужно в help-е или ещё где, но не в manе потому, что у меня manа нет. У меня windows если чё.
0
Псевдослучайный
1946 / 1146 / 98
Регистрация: 13.09.2011
Сообщений: 3,215
02.04.2013, 17:14
Ну, если ни ман почитать, ни хепл к линкеру посмотреть не в состоянии, остаётся только страдать.
0
быдлокодер
 Аватар для kravam
1724 / 911 / 106
Регистрация: 04.06.2008
Сообщений: 5,697
02.04.2013, 19:11  [ТС]
Вопрос не стоит "где прочесть про shared"

Так-то у меня и книжка есть "GCC._Полное_руководство_(Гриффитс)(2004 )", там по русски всё расписано если чё.

Вопрос стоит "где в прилагаемой документации прочесть про shared?". А то, что где-то у вас в manе написано, ну я очень рад.

А затем, что в следующий раз мне придётся искать инфу про другие опции, и где мне её брать? Или опять угадывать?

++++++++++++++++++++++++++++++++++++++++ ++++++++

Опять же help к линкёру. Третий раз: если это опция линкёра, почему она так не передаётся?
Bash
1
-Wl,--shared
Опять к какому-то мифическому ману отправите?

Добавлено через 1 час 48 минут
Короче я мало что понял, но что понял распишу. Итак, читаем:
Bash
1
Use '-v --help' to display command line options of sub-processes
Командуем:
Bash
1
g++ -v --help
Наблюдаем простыню. Может, я что-то путаю, но мне кажется тут ВСЁ. Ищем -shared:
Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
The following options are language-independent:
...
  -shared                     Create a shared library
...
Usage: e:/dev_cpp_nomingw/bin/../lib/gcc/mingw32/4.6.2/../../../../mingw32/bin/as.exe [option...] [asmfile...]
...
Usage: e:/dev_cpp_nomingw/bin/../lib/gcc/mingw32/4.6.2/../../../../mingw32/bin/ld.exe [options] file...
...
  -shared, -Bshareable        Create a shared library
e:/dev_cpp_nomingw/bin/../lib/gcc/mingw32/4.6.2/../../../../mingw32/bin/ld.exe: emulation specific options:
...
  --kill-at                          Remove @nn from exported symbols
...
Осторожно сделаю несколько выводов
1) -shared можно считать как опцией g++, так и опцией ld; что написано то и говорю. Причём неважно, используется ли НА САМОМ ДЕЛЕ -shared g++ или сразу передаётся в ld.

2) Поэтому смело используем КАК ОПЦИЮ g++

3) Почему -shared не выводится по g++ --help- чёрт его знает

4) К сожалению, что такое ld.exe: emulation и чем оно отличается от просто ld, мне непонятно. А отличия важные есть: так, например, --kill-at передаётся именно способом, которым я и предполагал передать -shared: -Wl,--kill-at. Не потому ли, что --kill-at присутствует в разделе ld.exe: emulation, а -shared не присутствует? Чёрт его знает, надо узнать, что это за раздел такой, а это проблематично.
0
Эксперт С++
4986 / 3093 / 456
Регистрация: 10.11.2010
Сообщений: 11,170
Записей в блоге: 10
05.04.2013, 18:03
Цитата Сообщение от kravam Посмотреть сообщение
3) Почему -shared не выводится по g++ --help- чёрт его знает
Кликните здесь для просмотра всего текста
Bash
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
g++ --help
Usage: g++.EXE [options] file...
Options:
  -pass-exit-codes         Exit with highest error code from a phase
  --help                   Display this information
  --target-help            Display target specific command line options
  --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...]
                           Display specific types of command line options
  (Use '-v --help' to display command line options of sub-processes)
  --version                Display compiler version information
  -dumpspecs               Display all of the built in spec strings
  -dumpversion             Display the version of the compiler
  -dumpmachine             Display the compiler's target processor
  -print-search-dirs       Display the directories in the compiler's search path
  -print-libgcc-file-name  Display the name of the compiler's companion library
  -print-file-name=<lib>   Display the full path to library <lib>
  -print-prog-name=<prog>  Display the full path to compiler component <prog>
  -print-multi-directory   Display the root directory for versions of libgcc
  -print-multi-lib         Display the mapping between command line options and
                           multiple library search directories
  -print-multi-os-directory Display the relative path to OS libraries
  -print-sysroot           Display the target libraries directory
  -print-sysroot-headers-suffix Display the sysroot suffix used to find headers
  -Wa,<options>            Pass comma-separated <options> on to the assembler
  -Wp,<options>            Pass comma-separated <options> on to the preprocessor
  -Wl,<options>            Pass comma-separated <options> on to the linker
  -Xassembler <arg>        Pass <arg> on to the assembler
  -Xpreprocessor <arg>     Pass <arg> on to the preprocessor
  -Xlinker <arg>           Pass <arg> on to the linker
  -save-temps              Do not delete intermediate files
  -save-temps=<arg>        Do not delete intermediate files
  -no-canonical-prefixes   Do not canonicalize paths when building relative
                           prefixes to other gcc components
  -pipe                    Use pipes rather than intermediate files
  -time                    Time the execution of each subprocess
  -specs=<file>            Override built-in specs with the contents of <file>
  -std=<standard>          Assume that the input sources are for <standard>
  --sysroot=<directory>    Use <directory> as the root directory for headers
                           and libraries
  -B <directory>           Add <directory> to the compiler's search paths
  -v                       Display the programs invoked by the compiler
  -###                     Like -v but options quoted and commands not executed
  -E                       Preprocess only; do not compile, assemble or link
  -S                       Compile only; do not assemble or link
  -c                       Compile and assemble, but do not link
  -o <file>                Place the output into <file>
  -pie                     Create a position independent executable
  -shared                  Create a shared library
  -x <language>            Specify the language of the following input files
                           Permissible languages include: c c++ assembler none
                           'none' means revert to the default behavior of
                           guessing the language based on the file's extension
 
Options starting with -g, -f, -m, -O, -W, or --param are automatically
 passed on to the various sub-processes invoked by g++.EXE.  In order to pass
 other options on to these processes the -W<letter> options must be used.
 
For bug reporting instructions, please see:
<http://sourceforge.net/projects/mingwbuilds/>.

48-я строка.
GCC 4.7.2
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
05.04.2013, 18:03
Помогаю со студенческими работами здесь

Как определить ширину блока для каждого экрана в пикселях, если она прописана в процентах?
Как определить ширину блока для каждого экрана в пикселях, если она прописана в процентах? Просто задача - вставить в блок для...

Опция компилятора, позволяющая временно отключить остановку выполнения программы, запущенной из IDE
нет опции компилятора , чтобы временно отключить остановку выполнения программы в запущенной из IDE т.е. аналога : ...

ActiveX Document DLL.Результат видет только на компах, где прописана dll
Пробовал создать, получил *.vbd и *.dll На Web сервере запускаю vbd - все ОК. Результат видет только на компах, где прописана dll...

Опция "SHARE" - для чего она
Здравствуйте. Собственно я создал этот топик, потому что не могу разобраться с функцией &quot;share&quot;, расположенной на правой стороне...

Отображалась не только выбранная опция, но и выводилось сообщение, которая опция была активной перед этим
Всем привет! Нужен совет. У меня есть код программы: есть 3 элемента RaddioButton, в зависимости какой RaddioButton я выберу(1, 2 или...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
8
Ответ Создать тему
Опции темы

Новые блоги и статьи
Расскажи мне о Мире, бродяга
kumehtar 12.11.2025
— Расскажи мне о Мире, бродяга, Ты же видел моря и метели. Как сменялись короны и стяги, Как эпохи стрелою летели. - Этот мир — это крылья и горы, Снег и пламя, любовь и тревоги, И бескрайние. . .
PowerShell Snippets
iNNOKENTIY21 11.11.2025
Модуль PowerShell 5. 1+ : Snippets. psm1 У меня модуль расположен в пользовательской папке модулей, по умолчанию: \Documents\WindowsPowerShell\Modules\Snippets\ А в самом низу файла-профиля. . .
PowerShell и онлайн сервисы. Валюта (floatrates.com руб.)
iNNOKENTIY21 11.11.2025
PowerShell функция floatrates-rub Примеры вызова: # Указанная валюта 'EUR' floatrates-rub -Code 'EUR' # Список имеющихся кодов валют floatrates-rub -Available function floatrates-rub {
PowerShell и онлайн сервисы. Погода (RP5.ru)
iNNOKENTIY21 11.11.2025
PowerShell функция Get-WeatherRP5rss для получения погоды с сервиса RP5 Примеры вызова Get-WeatherRP5rss с указанием id 5484 — Москва (восток, Измайлово) и переносом строки:. . .
PowerShell и онлайн сервисы. Погода (wttr)
iNNOKENTIY21 11.11.2025
PowerShell Функция для получения погоды с сервиса wttr Примеры вызова: Погода в городе Омск с прогнозом на день, можно изменить прогноз на более дней, для этого надо поменять запрос:. . .
PowerShell и онлайн сервисы. Валюта (ЦБР)
iNNOKENTIY21 11.11.2025
# Получение курса валют function cbr (] $Valutes = @('USD', 'EUR', 'CNY')) { $url = 'https:/ / www. cbr-xml-daily. ru/ daily_json. js' $data = Invoke-RestMethod -Uri $url $esc = 27 . . .
И решил я переделать этот ноут в машину для распределенных вычислений
Programma_Boinc 09.11.2025
И решил я переделать этот ноут в машину для распределенных вычислений Всем привет. А вот мой компьютер, переделанный из ноутбука. Был у меня ноут асус 2011 года. Со временем корпус превратился. . .
Мысли в слух
kumehtar 07.11.2025
Заметил среди людей, что по-настоящему верная дружба бывает между теми, с кем нечего делить.
Новая зверюга
volvo 07.11.2025
Подарок на Хеллоуин, и теперь у нас кроме Tuxedo Cat есть еще и щенок далматинца: Хочу еще Симбу взять, очень нравится. . .
Инференс ML моделей в Java: TensorFlow, DL4J и DJL
Javaican 05.11.2025
Python захватил мир машинного обучения - это факт. Но когда дело доходит до продакшена, ситуация не так однозначна. Помню проект в крупном банке три года назад: команда data science натренировала. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru