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;
- main.cpp - the main file.
- add.cpp - the function that we want to include or import.
- 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
#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.
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.