C++ 如何使用库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10358745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:56:33  来源:igfitidea点击:

How to use Libraries

c++windowsmacos

提问by sinθ

For some reason I'm never able to use external libraries in any language. I'm looking for instructions/explanations of how to use external libraries, as well as how they work. When I search online, I get fragments that never seem to apply to whatever library I download and try and use. I work on both a mac and a pc, and C++ examples are fine. I use eclipse IDE with the C++ plug in. If there are instructions that apply to all libraries that would be great.

出于某种原因,我永远无法使用任何语言的外部库。我正在寻找有关如何使用外部库以及它们如何工作的说明/解释。当我在线搜索时,我得到的片段似乎永远不会适用于我下载和尝试使用的任何库。我在 mac 和 pc 上工作,C++ 示例很好。我使用带有 C++ 插件的 Eclipse IDE。如果有适用于所有库的说明,那就太好了。

回答by Vincenzo Pii

Say you have a class Unusefuldefined as follows:

假设您有一个Unuseful定义如下的类:

File Unuseful.h:

文件Unuseful.h

class Unuseful {
public:
    void printUnusefulStatement();
};

File Unuseful.cpp:

文件Unuseful.cpp

#include "unuseful.h"
#include <iostream>

void Unuseful::printUnusefulStatement()
{
    std::cout << "Hello world!" << std::endl;
}

Now, you have another class that needs printing unuseful statements:

现在,您有另一个需要打印无用语句的类:

Unuseful u;
u.printUnusefulStatement();

This means that you want to use an external library containing the specific implementation (printUnusefulStatement) that you want to include in your code.

这意味着您要使用包含printUnusefulStatement要包含在代码中的特定实现 ( )的外部库。

You may use this library in two ways:

你可以通过两种方式使用这个库:

  1. By providing the source code to the compiler
  2. By providing a binary file (which had been previously compiled for your architecture), to the linker
  1. 通过向编译器提供源代码
  2. 通过向链接器提供二进制文件(之前已为您的架构编译过)

Case 1: using a library at compile time

案例 1:在编译时使用库

This is the simplest case. You have the source code of the library you have to use and you simply have to compile it together with your existing code (say main.cppfile). Typically you are the author and user of the library (a class that accomplishes a task you need).

这是最简单的情况。您拥有必须使用的库的源代码,只需将其与现有代码(例如main.cpp文件)一起编译即可。通常,您是库(完成您需要的任务的类)的作者和用户。

Compiling with this command:

用这个命令编译:

g++ main.cpp unuseful.cpp

allows you to use the implementation you need in your main.cppfile.

允许您在main.cpp文件中使用所需的实现。

Case 2: linking a library

案例 2:链接库

More often than Case 1, you don't have the source code of the library you want to use. You only have the header file (Unuseful.h, to continue with the example) and a staticor sharedlibrary (probably[*] libunuseful.aand libunuseful.sofiles, respectively).

Case 1更常见的是,您没有想要使用的库的源代码。您只有头文件(Unuseful.h,继续示例)和静态共享库(分别可能是 [*]libunuseful.alibunuseful.so文件)。

The static library is an archive of object files (*.o) that are linked inside your final executables, the shared libraries instead are loaded dynamically - at run time (look at this pagefor a better understanding of the difference).

静态库是*.o在最终可执行文件中链接的目标文件 ( )的存档,共享库是动态加载的 - 在运行时(查看此页面以更好地了解差异)。

Static libraries are created by simply archiving the *.ofiles with the arprogram:

静态库是通过简单地*.o使用ar程序归档文件来创建的:

# Create the object files (only one here)
g++ -c unuseful.cpp
# Create the archive (insert the lib prefix)
ar rcs libunuseful.a unuseful.o

Shared libraries are created with the g++-sharedoption:

使用以下g++-shared选项创建共享库:

# Create the object file with Position Independent Code[**]
g++ -fPIC -c unuseful.cpp
# Crate the shared library (insert the lib prefix)
g++ -shared -o libunuseful.so unuseful.o

Let's suppose now you have the Unuseful.hfile and the shared library (libunuseful.sofile) and you have a main.cppfile that instantiates a Unusefulobject and calls the printUnusefulStatementmethod.

假设现在您拥有Unuseful.h文件和共享库 ( libunuseful.sofile),并且您拥有一个main.cpp实例化Unuseful对象并调用该printUnusefulStatement方法的文件。

If you try to compile this file (g++ main.cpp) the linker will complain because it cannot find the printUnusefulStatementsymbol.

如果您尝试编译此文件 ( g++ main.cpp),链接器将抱怨,因为它找不到printUnusefulStatement符号。

It's time to use the library:

是时候使用库了:

g++ main.cpp -L. -lunuseful

The -Loption tells the linker where to search for library files and the -lflag tells the linker the name of the libraries to be used (without the libprefix).

-L选项告诉链接器在哪里搜索库文件,-l标志告诉链接器要使用的库的名称(不带lib前缀)。

Now the executable (a.out, because I didn't specify a different name) is created, and you have used a library to implement a functionality you needed (printUnusefulStatement).

现在创建了可执行文件 ( a.out,因为我没有指定不同的名称),并且您已经使用了一个库来实现您需要的功能 ( printUnusefulStatement)。

Since the shared library is loaded at run-time, the execution of the a.outexecutable may fail because the system is not able to find the library. Typically this can be solved by appropriately setting an environment variable indicating which paths to use to search for dynamic libraries:

由于共享库是在运行时加载的,a.out可执行文件的执行可能会因为系统无法找到该库而失败。通常,这可以通过适当设置环境变量来解决,该变量指示使用哪些路径来搜索动态库:

# Set the LD_LIBRARY_PATH [*]
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.

Done, now your executable has been compiled and it will be able to run and load the library it needs.

完成,现在您的可执行文件已经编译,它将能够运行和加载它需要的库。

Conclusion

结论

This is a rapid overview on libraries which I hope can help you understand how they are used and provided to others.

这是对库的快速概述,我希望可以帮助您了解它们是如何被使用和提供给其他人的。

There are many many aspects that should be investigated in more detail, if you are interested: g++options when creating shared libraries, aroptions, environment variables, the shared libraries format and so on.

如果您感兴趣,有许多方面应该更详细地研究:g++创建共享库时的ar选项、选项、环境变量、共享库格式等。

[*]: In a Unix environment

[*]:在 Unix 环境中

[**]: If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on the m68k, PowerPC and SPARC. Position-independent code requires special support, and therefore works only on certain machines. [From the g++ man page]

[**]:如果目标机器支持,则发出位置无关代码,适用于动态链接并避免对全局偏移表的大小进行任何限制。此选项在 m68k、PowerPC 和 SPARC 上有所不同。位置无关代码需要特殊支持,因此只能在某些机器上工作。[来自 g++ 手册页]

回答by Viktor Latypov

Here's where you start http://en.wikipedia.org/wiki/Library_(computing)

这是你开始的地方 http://en.wikipedia.org/wiki/Library_(computing)

Basically, a 'library' is a collection of compiled functions and class declarations.

基本上,“库”是已编译函数和类声明的集合。

On a Mac there are also "frameworks" which are somewhat similar to Pascal's units and contain both the declarations and the compiled code.

在 Mac 上也有“框架”,它们有点类似于 Pascal 的单位,包含声明和编译代码。

In managed languages like Java or C# there are packages and assemblies. Both are closely related to libraries.

在 Java 或 C# 等托管语言中,存在包和程序集。两者都与图书馆密切相关。

To use libraries in C or C++ you've got to have a .lib-file (or .a-file for most POSIX or GCC toolchain based compilers) and the prototypes of the functions which are compiled into the .lib file. Depending on your development environment (for Eclipse you are most likely using the GCC compiler and GNU toolchain with LD linker), you just specify the library files (.lib or .a) as the input to the linker. Most of the time the library is accompanied with header files which contain the definitions of function prototypes.

要在 C 或 C++ 中使用库,您必须有一个 .lib 文件(或 .a 文件,用于大多数基于 POSIX 或 GCC 工具链的编译器)和编译到 .lib 文件中的函数原型。根据您的开发环境(对于 Eclipse,您最有可能使用 GCC 编译器和带有 LD 链接器的 GNU 工具链),您只需指定库文件(.lib 或 .a)作为链接器的输入。大多数情况下,库都带有包含函数原型定义的头文件。

Even if you did not know about the linker, which is strange enough, the libraries are still used in your program implicitly - the std::cout is in the libstdc++ or the C Run-Time Library.

即使你不知道链接器,这很奇怪,这些库仍然在你的程序中隐式使用 - std::cout 在 libstdc++ 或 C 运行时库中。

As an example of a huge library and a useful set of C++ classes you might want to look at Boost.

作为一个巨大的库和一组有用的 C++ 类的例子,你可能想看看 Boost。

To write GUI on Windows you can use the WinAPI which is described in MSDN.

要在 Windows 上编写 GUI,您可以使用 MSDN 中描述的 WinAPI。

To write GUI on Mac you can use Carbon API which is somewhat similar to WinAPI, but is now deprecated. The only way to write "legit" GUI for MacOS is to use Cocoa and Objective-C.

要在 Mac 上编写 GUI,您可以使用 Carbon API,它有点类似于 WinAPI,但现在已弃用。为 MacOS 编写“合法”GUI 的唯一方法是使用 Cocoa 和 Objective-C。

To write cross-platform GUI you can use a lot of libraries: Qt, wxWidgets, GTK among them.

要编写跨平台 GUI,您可以使用很多库:Qt、wxWidgets、GTK 其中。

The last, but not the least. C++ is not the best language for GUI.

最后的但并非最不重要的。C++ 不是 GUI 的最佳语言。

回答by adem

The best way to use external C++ libraries is make use of a C++ package manager, go and learn of these;

使用外部 C++ 库的最好方法是使用 C++ 包管理器,去学习这些;

Some of them involve using CMake, you can find a well written tutorial on it here.

其中一些涉及使用 CMake,您可以在此处找到写得很好的教程。

.

.