0

How does this work-

I #include<cmath> and call pow(x,y) and it works. Now I create my own header file-

#ifndef HEADER_H
#define HEADER_H
void fun();
#endif

Its implementation is stored in header.cpp file. This is main.cpp where I will call fun()-

#include "header.h"
int main(){
fun();
return 0;
}

And now if I compiled and linked my file like this-

g++ -Wall main.cpp -o Main

Then this will not work because implementation(header.cpp) of fun() is missing.

For the fun() function to work I need to do this-

g++ -Wall header.cpp main.cpp -o Main

I am told that header files are supposed to store only the interface. (Why?)

So, <cmath> being a header should also contain only declaration of pow(x,y) function. But when I call pow(x,y) then it compiles without error and works fine. (How?)

To summarise, I have 3 questions-

1.Why are header files supposed to contain only interface? What bad can happen if I included interface and implementation in the same file?

2.How is built-in <cmath> different from a user-defined "header.h" ?

3.Why not directly include header.cpp in main.cpp?

avm
  • 387
  • 3
  • 16
  • 2
    Does this answer your question? https://stackoverflow.com/questions/1305947/why-does-c-need-a-separate-header-file – 463035818_is_not_an_ai May 28 '21 at 10:21
  • `2.How is built-in different from a user-defined "header.h" ?` it is not. It is part of the standard library, to which the compiler automatically link against. – t.niese May 28 '21 at 10:25
  • better focus on one question per question. Often the answer to one question already helps to understand the others. Problem is now that your questions have already been answered, but unlikely all three in that combination – 463035818_is_not_an_ai May 28 '21 at 10:27
  • 1
    *2.How is built-in `` different from a user-defined `"header.h"`?* The built-in `` could be in a file, or it could be "baked in" to the compiler. Because it doesn't have to be a file. (For Visual Studio, Clang, and GCC, it is in a file.) The `<>` indicate it is looked up in the *system path*, whereas the `""` indicate the file is looked up first in the *user path*, and failing that the *system path*. – Eljay May 28 '21 at 11:02
  • @FlorianWinter Almost yes. Reading that thread another question popped in my head- how does compiler search for implementation of pow(x,y) while linking? Does it search thru the whole specified(maybe by system or compiler)directory? If yes then is it not going to add up some time for searching and matching the correct implementation in all the available libraries? – avm May 28 '21 at 11:53

0 Answers0