0

header file contains declaration of a method and library contains the implementation of that method .I saw a video on Youtube on how to create our own header files, but in that video he was also giving the implementation. My question is that we are creating our own header files then we should also create a library corresponding to our own header files. how to do so?

  • 2
    You should create header files but you should spend some time to learn the language before you move to libraries. My advice is to stay away from youtube videos and instead get a few good `c++` books and read them from the beginning. [https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – drescherjm Aug 31 '19 at 12:22
  • libraries also are dependent on the compiler & linker that you use. – drescherjm Aug 31 '19 at 12:27

2 Answers2

2

It is indeed recommended to separate the implementation from the declaration. You don't need to create a library to do that. You can simply write the declaration in a header file and the implementation in a source file.

For example

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"
}

You don't have to call your header file "header.h" and you don't have to call your source file "source.cpp"


How to make a library

There are two types of libraries.

Static library

static libraries are libraries linked at buildtime. The steps to make one depend on your IDE. Assuming you use Visual Studio IDE check out this walkthrough.

Dynamic library

dynamic libraries are libraries linked at runtime. The steps to make and use one depends on your IDE and platform. Assuming you use Visual Studio IDE on Windows check out this walkthrough

tomer zeitune
  • 1,080
  • 1
  • 12
  • 14
0

In c++, you will usually find header (.h) and source (.cpp) file pairs. You are correct that the source files are used for the implementation. See Using G++ to compile multiple .cpp and .h files if you want to compile.

A small example:

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;
}
Ben Jones
  • 652
  • 6
  • 21