I just started learning C++ and I have been doing some practice on using user-defined header files. I just made a simple code on doing math operations. Many videos online use #include "filename.h
in their main program without even "connecting" the functions file with its header file. For instance, in my practice, I made two files, one called main.cpp and the other called math.cpp which has a header file called math.h. All these files are under one folder.
math.cpp
int add (int x, int y){
return x + y;
}
int sub(int x, int y){
return x - y ;
}
int multiply(int x, int y){
return x * y;
}
math.h
#pragma once
int add (int x, int y);
int sub(int x, int y);
int multiply(int x, int y);
main.cpp
#include <iostream>
#include "math.h"
using namespace std;
int main (){
cout << add(1,2);
return 0;
}
Interestingly, if I write #include "math.cpp"
in the math.h file, it works without any errors but I have read countless times that this should not be done. Additionally, many tutorials do not even "connect" the header and the cpp file and just include the header in the main file. When I try to do this, it doesn't work. The only time it works is when I change the math.h code to
#pragma once
#include "math.cpp"
int add (int x, int y);
int sub(int x, int y);
int multiply(int x, int y);
I am still not entirely sure what the syntax should be when using user-defined header files. How does the header file we create know which cpp file to look at? Does it have anything to do with the fact I am using macOS that none of the tutorials seem to work?