Pragma comment lib linux

#pragma comment (lib, «xxx.lib» ) эквивалент Linux?

У меня есть файл статической библиотеки с именем libunp.a , я знаю, что я мог бы использовать gcc -lunp xx для ссылки на библиотеку.

Я мог бы использовать #pragma comment(lib,»xxx.lib») , чтобы сообщить компилятору Microsoft C/С++ о включении библиотеки; как я могу это сделать в Linux/GCC?

Библиотеки должны быть указаны на этапе связывания. Такая информация просто не входит в единицу перевода. Блок перевода может быть предварительно обработан, скомпилированы и собраны даже без стадии связывания.

Просто потому, что #pragma comment(lib,»xxx.lib») находится в исходном файле, это не значит, что компилятор его использует. Фактически, это идет как комментарий и впоследствии используется компоновщиком. Не сильно отличается от * nix.

Кажется, что никаких упоминаний о каких-либо эквивалентных прагмах в странице руководства GCC в прагмах.

Одна из причин, по которой я видел, что GCC не поддерживает ссылку в исходном коде, заключалась в том, что иногда правильная привязка зависит от порядка ссылок; и это потребует от вас убедиться, что порядок связывания происходит правильно, независимо от порядка компиляции. Если вы собираетесь пойти на эту работу, вы можете просто передать аргументы компоновщика в командной строке (или иначе), я полагаю.

Простой; вы не можете. GCC не имеет такого эквивалента. Укажите -l как параметр gcc, создайте компоновщик script, вызовите ld , вызовите 911 или что-то еще.

Не то, чтобы такая прагма даже имела смысл. Библиотеки должны быть указаны на этапе связывания. Такая информация просто не принадлежит внутри единицы перевода. Блок перевода может быть предварительно обработан, скомпилирован и собран даже без стадии связывания. Инструментальная привязка, используемая Visual Studio, позволяет это, потому что это braindead и всегда выполняет привязку.

Возможно, вы захотите сохранить себе утомительную типизацию и создать MakeFile для своего проекта: GNU Make Manual

Источник

comment pragma

Вставляет запись комментария в объектный или исполняемый файл.

Синтаксис

#pragma comment( comment-Type [ , «Комментарий-Строка«] )

Remarks

Тип Comment — это один из стандартных идентификаторов, описанных ниже, который указывает тип записи комментария. Необязательный Комментарий-String — это строковый литерал, предоставляющий дополнительные сведения для некоторых типов комментариев. Так как Комментарий-Строка является строковым литералом, он подчиняется всем правилам для строковых литералов при использовании escape-символов, внедренных кавычек ( » ) и сцепления.

Читайте также:  Windows не производит оценку производительности

compiler

Задает в объектном файле имя и номер версии компилятора. Эта запись комментария игнорируется компоновщиком. Если для этого типа записей указан параметр строки Comment , компилятор выдает предупреждение.

Задает в объектном файле запись поиска библиотеки. Этот тип комментария должен сопровождаться параметром строки Comment с именем (и, возможно, путем) библиотеки, которую должен искать компоновщик. Имя библиотеки соответствует заданным по умолчанию записям поиска в объектном файле. Компоновщик ищет эту библиотеку точно так же, как если бы она была указана в командной строке, если библиотека не указана с помощью /nodefaultlib . Несколько записей поиска библиотеки можно поместить в один и тот же исходный файл. Каждая запись отображается в объектном файле в том же порядке, в котором он находится в исходном файле.

Если важен порядок использования библиотеки по умолчанию и добавленной библиотеки, при компиляции с /Zl параметром имя библиотеки по умолчанию не будет помещено в модуль объекта. pragmaЗатем можно использовать второй комментарий для вставки имени библиотеки по умолчанию после добавления библиотеки. Библиотеки, перечисленные с помощью этих pragma директив, будут отображаться в модуле объекта в том же порядке, в котором они находятся в исходном коде.

компоновщик

Помещает параметр компоновщика в объектный файл. Благодаря этому параметр компоновщика можно не передавать из командной строки и не указывать в среде разработки, а задать непосредственно в комментарии. Например, в нем можно задать параметр /include, чтобы принудительно включить символ:

Для передачи в идентификатор компоновщика доступны только следующие параметры компоновщика (comment-Type):

Источник

comment pragma

Places a comment record into an object file or executable file.

Syntax

#pragma comment( comment-type [ , «comment-string» ] )

Remarks

The comment-type is one of the predefined identifiers, described below, that specifies the type of comment record. The optional comment-string is a string literal that provides additional information for some comment types. Because comment-string is a string literal, it obeys all the rules for string literals on use of escape characters, embedded quotation marks ( » ), and concatenation.

compiler

Places the name and version number of the compiler in the object file. This comment record is ignored by the linker. If you supply a comment-string parameter for this record type, the compiler generates a warning.

Places a library-search record in the object file. This comment type must be accompanied by a comment-string parameter that has the name (and possibly the path) of the library that you want the linker to search. The library name follows the default library-search records in the object file. The linker searches for this library the same way as if you specified it on the command line, as long as the library isn’t specified by using /nodefaultlib . You can place multiple library-search records in the same source file. Each record appears in the object file in the same order it’s found in the source file.

Читайте также:  Windows 10 белые кружочки

If the order of the default library and an added library is important, compiling with the /Zl switch will prevent the default library name from being placed in the object module. A second comment pragma then can be used to insert the name of the default library after the added library. The libraries listed with these pragma directives will appear in the object module in the same order they’re found in the source code.

linker

Places a linker option in the object file. You can use this comment-type to specify a linker option instead of passing it to the command line or specifying it in the development environment. For example, you can specify the /include option to force the inclusion of a symbol:

Only the following (comment-type) linker options are available to be passed to the linker identifier:

Источник

What’s #pragma comment (lib, «lib/glut32.lib»)?

I saw the code on the top of a GLUT demo and I’m curious about its functionality.

Why would someone want to write a #pragma instead of just including the library?

3 Answers 3

This pragma allows the library author to define library imports based on a range of criteria that can be analysed at compile-time. For instance, you can link against different libs, based on whether you want to link with:

  • multithreading on or off;
  • the shared or static version of the library in question;
  • the shared or static version of the standard runtime library;
  • the debug or release library;
  • the 32-bit or 64-bit library.

With the pragma form, all this can be decided via #ifdef preprocessor tests in one of the library’s header files.

The #pragma is useful if you’re distributing a library. Especially if you have different compiled .libs for different build settings (e.g. debug vs. release, multi-threaded C runtime vs. single-threaded, DLL vs. static library, etc). You can use #ifdef s in your code to select the correct .lib file, rather than requiring your users to set up their build environment to select the correct one.

Читайте также:  Как добавить иконку linux mint

It reduces support time because your users cannot choose the wrong .lib file.

It’s an MSVC-specific pragma that means the named library will be automatically included at link time. The rest of your question about «just including the library» suggests that you’re not appreciating the difference between headers and libraries: the header ( GL/glut.h ) describes what functions the compiler can expect at link time. The library ( lib/glut32.lib ) provides the implementation of these functions.

As the other answers have explained, it can be convenient, but I personally consider it a terrible idea to use this because it adds another barrier to writing portable code (other platforms and compilers may not support it). This question (thanks, @martin clayton) explains why it’s not a good idea for portable code.

Источник

Relative path with #pragma comment(lib)

Using Visual Studio 2010, I’d like to specify a path in a #pragma comment(lib) relative to the cpp file including it.

in foo.cpp and it seems to work. However, this appears hackish to me.

Is there a less hackish way?

1 Answer 1

No, not if this needs to be relative from a .cpp file. Which is pretty unusual, you cannot normally guarantee that a .lib got deployed in a directory that’s relative from a client source code that uses the library. Although you can certainly give install instructions that stipulate this.

The normal way is to just specify «foo.lib» and have the linker configured to search the proper directory for the .lib file with the Additional Library Directories setting. Which allows the .lib to be deployed anywhere but the library user will have to update the setting when he sets up his project. This is otherwise a very normal configuration task. And not terribly different from specifying the library in the Additional Dependencies setting.

Keep in mind that the #pragma is typically most useful to help the client programmer to use the proper version of a static link library. You normally have to provide 4 builds of a static .lib, debug vs release and /MT vs /MD. Possibly multiplied by the number of VS versions you are willing to support. This can get hairy in a hurry. The _DLL, _DEBUG and _MSC_VER predefined macros help you to generate the correct #pragma.

Источник

Оцените статью