【问题标题】:header files and library files connection [duplicate]头文件和库文件连接[重复]
【发布时间】:2020-01-04 08:53:09
【问题描述】:

头文件包含方法的声明,库包含该方法的实现。我在 Youtube 上看到了一个关于如何创建我们自己的头文件的视频,但在那个视频中,他也给出了实现。我的问题是我们正在创建自己的头文件,那么我们还应该创建一个与我们自己的头文件相对应的库。怎么办?

【问题讨论】:

标签: c++


【解决方案1】:

确实建议将实现与声明分开。你不需要创建一个库来做到这一点。您可以简单地将声明写在头文件中,将实现写在源文件中。

例如

header.h:

#pragma once
void add(int first, int second);//this is a declaration for "add"

source.cpp:

#include "header.h"
void add(int first, int second) {
return first + second;//this is an implementation for "add"
}

您不必将头文件称为“header.h”,也不必将源文件称为“source.cpp”


如何制作图书馆

有两种类型的库。

静态库

静态库是在构建时链接的库。 制作步骤取决于您的 IDE。假设您使用 Visual Studio IDE,请查看 this walkthrough

动态库

动态库是在运行时链接的库。 制作和使用的步骤取决于您的 IDE 和平台。假设您在 Windows 上使用 Visual Studio IDE,请查看 this walkthrough

【讨论】:

    【解决方案2】:

    在 c++ 中,您通常会找到标头 (.h) 和源 (.cpp) 文件对。您是正确的,源文件用于实现。如果要编译,请参阅Using G++ to compile multiple .cpp and .h files

    一个小例子:

    MyClass.h:

    #ifndef MYCLASS_H   // These are called header guards
    #define MYCLASS_H
    
    class MyClass {
        // constructor
        MyClass();
    
        // member that prints "Hello, world."
        void hello();
    }
    
    #endif // MYCLASS_H
    

    MyClass.cpp

    #include "MyClass.h"
    #include <iostream>
    
    // Implementation of constructor
    MyClass::MyClass()
    {
        std::cout << "Constructed MyClass object." << std::endl;
    }
    
    // Implementation of hello
    void MyClass::hello()
    {
        std::cout << "Hello, World." << std::endl;
    }
    

    ma​​in.cpp

    #include "MyClass.h"
    
    int main(int argc, char** argv)
    {
        MyClass mc;
        mc.hello();
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-18
      • 2011-08-02
      • 2020-12-10
      • 2018-06-13
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      相关资源
      最近更新 更多