Compiling custom headers

I'm using Linux Ubuntu and compiling with G++ 4.8.2 if that helps

I've been playing around with creating my own header files, trial and error and reading online. I've run into something that's really confusing me:

Example 1 (this works):
1
2
3
4
  //myheader.h
  #pragma once
  
  int myfunction();


1
2
3
4
5
6
7
8
  //myheader.cpp
  #include"myheader.h"

  int myfunction()
  {
    // do whatever
    return aVariable;
  }


1
2
3
4
5
6
7
  //main.cpp
  #include"myheader.h"

  int main()
  {
    int a = myfunction();
  }


compile by running command:
 
g++ main.cpp

And it works perfectly

Example 2 (this is where I'm confused):
1
2
3
4
5
  //myheader.h
  #pragma once
  
  int myfunction();
  int myotherfunction();


1
2
3
4
5
6
7
8
9
10
11
12
13
14
  //myheader.cpp
  #include"myheader.h"

  int myfunction()
  {
    // do whatever
    return aVariable;
  }

  int myotherfunction()
  {
    // do whatever
    return anotherVariable;
  }


1
2
3
4
5
6
7
8
  //main.cpp
  #include"myheader.h"

  int main()
  {
    int a = myfunction();
    int b = myotherfunction();
  }


Compile by running command:
 
g++ main.cpp

And I get an compiler error about undefined references to the functions.


However, if I compile by using
 
g++ main.cpp myheader.cpp

it compiles and works as expected.

Why do I not need to add the header source file in the g++ compile command if there's only one function, but it needs it if I have more than one function?
Is there a way to do this, using multiple functions in the header, where I don't have to compile the source file along with my regular code?
Am I just totally missing the point of headers (very possible)?

Thanks so much to anyone who can shed some light on this for me.
Topic archived. No new replies allowed.