0

How can i create my library (or something like that), that I can save/edit and include it in my file. It should contain functions that I created and the main thing is that I can use them on my variables, for example:

I want to create a function:

appendString(string additionalText) - function in "library"

And to have a variable:

string myString = "Hello " - variable in file (in which I "included" library)

After that, I write:

myString.appendString("World");

So, at the end myString should be "Hello World".

PLEASE NOTE: THESE FUNCTIONS WILL BE CALLED ON BASIC DATA TYPES, NOT OBJECTS!

melpomene
  • 84,125
  • 8
  • 85
  • 148
ZenWoR
  • 13
  • 4
  • @super you don't `#include` a cpp file, you add it to your project's makefile instead – Remy Lebeau Jun 21 '18 at 22:06
  • Is your question "how can I make my own library?" or "how can I add new methods to an existing class?"? – melpomene Jun 21 '18 at 22:10
  • Or https://stackoverflow.com/questions/3487117/create-static-library-in-visual-c-express-2010, https://stackoverflow.com/questions/47603272/creating-c-library-with-cmake, etc. We already have a lot of answers - nothing personal Luka. – MSalters Jun 21 '18 at 22:12

1 Answers1

0

string is a class type, not a "basic data type", as evident by the fact that you are calling a member method on it. Basic types don't have methods.

You can't add new methods to an existing class type, you would have to derive a new class from it. However, STL containers like std::string are not designed to be derived from (no virtual destructors, etc).

It would make more sense to implement your appendString() function like this 1:

void appendString(string &text, const string &additionalText)

And then call it like this:

appendString(myString, "World");

1: std::string already has several append() methods, eg: myString.append("World");

In any case, to answer your question, you can write a pair of .h/.cpp files, where the .h file declares your custom functions and types, and the .cpp file implements them.

Then, you can #include the .h wherever you need it, and either

  1. add the .cpp file to each project.

  2. compile the .cpp into a static .lib file (or equivalent, depending on compiler and target platform) that you can then link into each project's final executable.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Thank you very much! Your answer is clear and you answered really fast! I will sure try it out, because I think this is what i need! Thank you once more! – ZenWoR Jun 21 '18 at 22:42