Use lib pragma windows

comment pragma comment pragma

Вставляет запись комментария в объектный или исполняемый файл. Places a comment record into an object file or executable file.

Синтаксис Syntax

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

Примечания Remarks

Тип Comment — это один из стандартных идентификаторов, описанных ниже, который указывает тип записи комментария. The comment-type is one of the predefined identifiers, described below, that specifies the type of comment record. Необязательный Комментарий-String — это строковый литерал, предоставляющий дополнительные сведения для некоторых типов комментариев. The optional comment-string is a string literal that provides additional information for some comment types. Так как Комментарий-Строка является строковым литералом, он подчиняется всем правилам для строковых литералов при использовании escape-символов, внедренных кавычек ( » ) и сцепления. 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 compiler

Задает в объектном файле имя и номер версии компилятора. Places the name and version number of the compiler in the object file. Эта запись комментария игнорируется компоновщиком. This comment record is ignored by the linker. Если для этого типа записей указан параметр строки Comment , компилятор выдает предупреждение. If you supply a comment-string parameter for this record type, the compiler generates a warning.

lib lib

Задает в объектном файле запись поиска библиотеки. Places a library-search record in the object file. Этот тип комментария должен сопровождаться параметром строки Comment с именем (и, возможно, путем) библиотеки, которую должен искать компоновщик. 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. Компоновщик ищет эту библиотеку точно так же, как если бы она была указана в командной строке, если библиотека не указана с помощью /nodefaultlib . 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.

Если важен порядок использования библиотеки по умолчанию и добавленной библиотеки, при компиляции с /Zl параметром имя библиотеки по умолчанию не будет помещено в модуль объекта. 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. pragmaЗатем можно использовать второй комментарий для вставки имени библиотеки по умолчанию после добавления библиотеки. A second comment pragma then can be used to insert the name of the default library after the added library. Библиотеки, перечисленные с помощью этих pragma директив, будут отображаться в модуле объекта в том же порядке, в котором они находятся в исходном коде. The libraries listed with these pragma directives will appear in the object module in the same order they’re found in the source code.

Читайте также:  Как удалить vipnet client полностью linux

компоновщик 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. Например, в нем можно задать параметр /include, чтобы принудительно включить символ: For example, you can specify the /include option to force the inclusion of a symbol:

Для передачи в идентификатор компоновщика доступны только следующие параметры компоновщика (comment-Type): Only the following (comment-type) linker options are available to be passed to the linker identifier:

Директивы pragma и __pragma _Pragma Ключевые слова и Pragma directives and the __pragma and _Pragma keywords

Директивы директивы pragma определяют функции компилятора, зависящие от конкретного компьютера или операционной системы. Pragma directives specify machine-specific or operating system-specific compiler features. __pragma Ключевое слово, относящееся только к компилятору Майкрософт, позволяет создавать pragma директивы кода внутри определений макросов. The __pragma keyword, which is specific to the Microsoft compiler, enables you to code pragma directives within macro definitions. Стандартный _Pragma Оператор препроцессора появился в C99 и принят в c++ 11. The standard _Pragma preprocessor operator was introduced in C99 and adopted by C++11.

Синтаксис Syntax

* #pragma ***Строка токена #pragma token-string
* __pragma( ***строка ) токена два подчеркивания в начале — конкретное расширение Майкрософт __pragma( token-string ) // two leading underscores — Microsoft specific extension
* _Pragma( ***строковый литерал ) C99 _Pragma( string-literal ) // C99

Примечания Remarks

Каждая реализация C и C++ поддерживает некоторые возможности, уникальные для хост-компьютера или операционной системы. Each implementation of C and C++ supports some features unique to its host machine or operating system. Некоторые программы, например, должны выполнять точный контроль над расположением данных в памяти или управлять способом получения параметров определенными функциями. Some programs, for example, must exercise precise control over the location of data in memory, or control the way certain functions receive parameters. #pragma Директивы предлагают каждому компилятору возможность предоставлять функции для конкретного компьютера и операционной системы, сохраняя общую совместимость с языками C и C++. The #pragma directives offer a way for each compiler to offer machine- and operating system-specific features, while maintaining overall compatibility with the C and C++ languages.

Директивы директивы pragma зависят от конкретного компьютера или операционной системы и обычно отличаются для каждого компилятора. Pragma directives are machine-specific or operating system-specific by definition, and are typically different for every compiler. pragmaМожно использовать в условной директиве для предоставления новых функций препроцессора. A pragma can be used in a conditional directive, to provide new preprocessor functionality. Или используйте один из них, чтобы предоставить компилятору сведения, определяемые реализацией. Or, use one to provide implementation-defined information to the compiler.

Строка токена — это последовательность символов, представляющая конкретную инструкцию компилятора и аргументы, если таковые имеются. The token-string is a series of characters representing a specific compiler instruction and arguments, if any. Знак решетки ( # ) должен быть первым символом, не являющимся пробелом, в строке, содержащей pragma . The number sign ( # ) must be the first non-white-space character on the line that contains the pragma. Символы пробела могут разделять знак решетки и слово « pragma ». White-space characters can separate the number sign and the word «pragma». Далее #pragma напишите любой текст, который переводчик может проанализировать в виде токенов предварительной обработки. Following #pragma , write any text that the translator can parse as preprocessing tokens. Аргумент для #pragma заключается в расширении макроса. The argument to #pragma is subject to macro expansion.

Читайте также:  Синий экран смерти ошибка 0x000000ed windows

Строка-литерал — это входные данные _Pragma . The string-literal is the input to _Pragma . Внешние кавычки и начальные и конечные пробелы удаляются. Outer quotes and leading/trailing whitespace are removed. \» заменяется на » и \\ заменяется на \ . \» is replaced with » and \\ is replaced with \ .

Компилятор выдает предупреждение при обнаружении того pragma , что оно не распознается, и продолжит компиляцию. The compiler issues a warning when it finds a pragma that it doesn’t recognize, and continues compilation.

Компиляторы Microsoft C и C++ распознают следующие pragma директивы: The Microsoft C and C++ compilers recognize the following pragma directives:

1 поддерживается только компилятором C++. 1 Supported only by the C++ compiler.

Директивы pragma и параметры компилятора Pragma directives and compiler options

Некоторые pragma директивы предоставляют те же функциональные возможности, что и параметры компилятора. Some pragma directives provide the same functionality as compiler options. Когда в pragma исходном коде достигается, он переопределяет поведение, заданное параметром компилятора. When a pragma is reached in source code, it overrides the behavior specified by the compiler option. Например, если указано /Zp8 , можно переопределить этот параметр компилятора для определенных разделов кода pack : For example, if you specified /Zp8 , you can override this compiler setting for specific sections of the code with pack :

ключевое слово __pragma() ; The __pragma() keyword

Компилятор также поддерживает __pragma ключевое слово Microsoft, которое имеет те же функциональные возможности, что и #pragma директива. The compiler also supports the Microsoft-specific __pragma keyword, which has the same functionality as the #pragma directive. Разница заключается в том, что __pragma ключевое слово можно использовать в качестве встроенного в определении макроса. The difference is, the __pragma keyword is usable inline in a macro definition. #pragma Директива не может использоваться в определении макроса, так как компилятор интерпретирует символ решетки (#) в директиве как оператор строковый (#). The #pragma directive isn’t usable in a macro definition, because the compiler interprets the number sign character (‘#’) in the directive as the stringizing operator (#).

В следующем примере кода показано, как __pragma ключевое слово может использоваться в макросе. The following code example demonstrates how the __pragma keyword can be used in a macro. Этот код взят из заголовка мфкдуал. h в образце ACDUAL в «примеры поддержки компилятора COM»: This code is excerpted from the mfcdual.h header in the ACDUAL sample in «Compiler COM Support Samples»:

_Pragma Оператор предварительной обработки (C99, c++ 11) The _Pragma preprocessing operator (C99, C++11)

_Pragma Аналогично __pragma ключевому слову Microsoft, за исключением того, что оно является частью стандарта. _Pragma is similar to the Microsoft-specific __pragma keyword, except it’s part of the standard. Он появился для C в C99. It was introduced for C in C99. Для C++ оно было представлено в C++ 11. For C++, it was introduced in C++11.

Он позволяет размещать pragma директивы в определении макроса. It allows you to put pragma directives into a macro definition. Он содержит одну начальную подчеркивание _ вместо двух начальных подчеркивания __ , которое имеет ключевое слово Microsoft, а первая буква прописной. It has one leading underscore _ instead of two leading underscores __ that the Microsoft-specific keyword has, and the first letter is capitalized.

Читайте также:  Wsus windows 10 что выбрать

Строковый литерал должен быть таким же, как в противном случае после #pragma оператора. The string literal should be what you would otherwise put following a #pragma statement. Например: For example:

Кавычки и обратные косые черты должны быть экранированы, как показано выше. Quotation marks and back-slashes should be escaped, as shown above. pragmaСтрока, которая не распознана, игнорируется. A pragma string that isn’t recognized is ignored.

В следующем примере кода показано, как _Pragma ключевое слово можно использовать в макросе, похожем на утверждение, если не нужно получать предупреждение, если условие выражения имеет значение Constant. The following code example demonstrates how the _Pragma keyword could be used in an assert-like macro when you don’t want to get a warning when the condition expression happens to be constant.

В определении макроса используется do — while(0) идиома для макросов с несколькими операторами, чтобы его можно было использовать, как будто это одна инструкция. The macro definition uses the do — while(0) idiom for multi-statement macros so that it can be used as though it were one statement. Дополнительные сведения см. в разделе Многострочный макрос на языке C Stack Overflow. See C multi-line macro on Stack Overflow for more info. _Pragma Оператор применяется только к строке кода, следующей за ней. The _Pragma statement only applies to the line of code that follows it.

C++: What does #pragma comment(lib, “XXX”) actually do with “XXX”?

My background is C# but I have to maintain some legacy (MS) C++. In that codebase I stumpled across:

where 700 is some versioning. Besides the lib is a DLL with the same name.

I first thought that the program would be dependant upon the DLL but after removing it from the system the program still works. There exists a newer version of the DLL, though, which is named OtherLib900.

It seems as though the program ‘included’ the code of the lib so that it’s no longer dependant upon the external DLL. (Or that the program ‘automatically’ uses the newer DLL. )

Which one is correct? Is there are way to further confirm that ‘assumption’?

3 Answers 3

If a program has this pragma it will look for the library OtherLib700.lib . If that is an import library when the program is loaded windows will search for OtherLib700.dll in the path. It will not try to look for OtherLib900.dll during execution so it must be finding your dll in a different folder. This assumes that OtherLib700.lib is an import library and not a static library. If OtherLib700.lib is a static library then that is all it needs.

That pragma is used to link against the specified .lib file. This is an alternative to specifying the library in the external dependencies field in project settings.

Mostly, it’s used to support different versions:

When your application uses a dynamically-linked library, a lib file tells you information about what symbols are exported in the dll . So basically you only need the lib to compile & link, but you need the dll to run the program, as it contains all the binary code.

You say there’s an associated dll , which usually indicates the lib file only contains linking info, and no code. You should get a run-time error if the associated dll was not found. You can check with MSVS if a different version of the dll was loaded or if it was loaded from a different place.

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