Write a library without class and cpp file [closed]

Make sure your .h has a guard.

#pragma once

Either declare the function inline in your header:

inline int added (uint8_t a, uint8_t b){
  int r;
  r=a+b;
  return r;
}

Declaring it static works as well.

static int added (uint8_t a, uint8_t b){
  int r;
  r=a+b;
  return r;
}

Or, if your function is big, or you have a circular dependency, put its declaration only in the header file.

extern int added (uint8_t a, uint8_t b); // extern keyword is optional

and the body in a cpp file

int added (uint8_t a, uint8_t b){
  int r;
  r=a+b;
  return r;
}

It’s that simple.

Some compilers do not support #pragma once and to avoid the declarations inside the header file to appear twice when compiling a cpp (that could generate compiler warnings and errors), they use macros instead.

#ifndef FILENAME_H  // check if this header file was already read, using a unique macro name
#define FILENAME_H  // no. define the unique macro now, so we'll not read this section again

//  this section will only be read once.

#endif              // end the section protected by FILENAME_H

Leave a Comment