Labels

Android (1) bash (2) boost (2) C (34) C++ (2) cheatsheet (2) CLion (6) css (3) Debian (33) DL (17) Docker (1) Dreamweaver (2) Eclipse (3) fail2ban (4) git (5) GitHub (4) Hacking (3) html (8) http (1) iOS (1) iPad (1) IRC (1) Java (30) javascript (3) Linux (164) Mac (19) Machine Learning (1) mySQL (47) Netbeans (4) Networking (1) Nexus (1) OpenVMS (6) Oracle (1) Pandas (3) php (16) Postgresql (8) Python (9) raid (1) RedHat (14) Samba (2) Slackware (45) SQL (14) svn (1) tar (1) ThinkPad (1) Virtualbox (3) Visual Basic (1) Visual Studio (1) Windows (2)

Friday 26 June 2020

A basic C++ file with a header

What follows is a basic C++ file with a Header file


 -- taken from https://www.learncpp.com/cpp-tutorial/header-files/ --




There are three files;


  1. main.cpp - the main file.
  2. add.cpp - the function that we want to include or import.
  3. add.h - The header for for add.cpp

main.cpp


#include <iostream>
#include "add.h"

int main()
{
std::cout<< "The sum of 3 and 4 is " << add(3,4) <<std::endl;
return 0;
}


add.h


int  add (int x, int y);


add.cpp


int add(int x, int y)
{
return x + y;
}




Now compiling the above with g++ main.cpp produces the following error;



Undefined symbols for architecture x86_64:
  "add(int, int)", referenced from:
      _main in main-4335f8.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)



But if we do g++ *.cpp OR g++ main.cpp add.cpp it compiles just fine and gives us;

a.out

which of course we can run with ./a.out (we may need to make it executable first of course with chmod +x a.out)

Note: we can of course do g++ *.cpp -o output.o which will produce a binary output.o



What if we were to have our Header(s) in another directory?

The common sense thing would be to have out import/include looking like this:

#include "myLibs/add.h" OR #include "../add.h" or similar, while this will work, it is considered bad practice and we should do as below;


g++ myLibs/add.cpp main.cpp -I myLibs

Which is basically compiling myLibs/add.cpp and then main.cpp

Finally we use the -I option to tell the compiler that there is another directory, in our case myLibs and I believe this is so that when main.cpp has an include file, the compiler knows where to look to find said included file.



No comments:

Post a Comment

Note: only a member of this blog may post a comment.