using multiple source files

I'm experimenting using multiple source files. Here's a short example of what I think SHOULD work...:

1
2
3
4
5
6
7
8
9
10
///functions.h///

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

void print(char*);
int increment(int);
int sum(int,int);

#endif 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
///functions.cpp///

#ifndef FUNCTIONS_CPP
#define FUNCTIONS_CPP

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

void print(char* input)
{
  cout<<input<<endl;
}

int increment(int a)
{
  return (a+1);
}

int sum(int a, int b)
{
  return (a+b);
}

#endif 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
///main.cpp///

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

int main()
{
  print("hello world!");
  int foo=5;
  int foo2=increment(foo);
  cout<<"foo: "<<foo<<endl;
  cout<<"foo2: "<<foo2<<endl;

  cout<<"sum(foo,foo2): "<<sum(foo,foo2)<<endl;

  return 0;
}



This makes sense to me... But when i try compiling main.cpp I get a bunch of "Undefined symbols"

This leads me to think that the functions are not defined...

The program works as expected if I #include "functions.cpp" in main.cpp... but I thought one only had to include the .h file and the linker would link all the symbols for you...

Please correct me how I am wrong.
Try removing the protection from the .cpp file, you only need it for header files.
Sounds like you didn't add functions.cpp to the project.
oh good point about the protection on the cpp file... lol that was foolish.

Unfortunately, that didn't fix the issue...

and helios, I'm not really in a project environment... I'm using the command line like "g++ -o myProgram main.cpp"
Try g++ -o myProgram main.cpp functions.cpp
oh, nice call helios that worked.

Though it would be a little tedious to include every single .cpp file with the g++ command... is it safe to do "g++ -o myProgram *.cpp" ??
I'm not sure. I think it's worth a try.

And about the tediousness, that's exactly why the GNU build system was created.
well it did work when i tried it... so that's pretty neat.

kthx :D
Wheres the using namespace std;
oh.. good call Mythios.. I guess i forgot that.

Oh well, it was only supposed to be a rough example...
Topic archived. No new replies allowed.