头文件包含方法的声明,库包含该方法的实现。我在Youtube上观看了有关如何创建自己的头文件的视频,但在该视频中他也给出了实现。我的问题是,我们正在创建自己的头文件,然后还应该创建一个与我们自己的头文件相对应的库。怎么做?
答案 0 :(得分:2)
确实建议将实现与声明分开。您不需要创建一个库就可以做到这一点。您只需将声明写在头文件中,将实现写在源文件中。
例如
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
答案 1 :(得分:0)
在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;
}
main.cpp
#include "MyClass.h"
int main(int argc, char** argv)
{
MyClass mc;
mc.hello();
return 0;
}