How do I make a function global?

I want these two functions to be able to be usable by all my other .cpp files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef function_h
#define function_h

void clear()
{
	system("cls");
}
void pause()
{
	char a;
	a=getch();
}

#endif 


I have two .cpp files and two .h files. That code above this is one of the .h files. This is my other .h file.


1
2
3
4
5
6
7
8
9
10
11
12
#ifndef UserInterface_h
#define UserInterface_h
#include <string>
#include <iostream>
#include <conio.h>
using namespace std;
class UI // User interface
{
...
};

#endif 


This is the .cpp:
1
2
3
4
5
#include "UserInterface.h"
#include "functions.h"
using namespace std;

...//pause() and clear() are both used here 


This is my main

1
2
3
4
5
6
7
#include "UserInterface.h"
#include "functions.h"

using namespace std;

int main()
{...}//pause() is used in main 


I'm getting an error

1>UserInterface.obj : error LNK2005: "void __cdecl clear(void)" (?clear@@YAXXZ) already defined in main.obj
1>UserInterface.obj : error LNK2005: "void __cdecl pause(void)" (?pause@@YAXXZ) already defined in main.obj
1>C:\Users\MyName\Documents\Visual Studio 2010\Projects\experiment\Debug\UserInterface.exe : fatal error LNK1169: one or more multiply defined symbols found
Last edited on
Declare the functions in the header
1
2
3
4
5
6
7
#ifndef function_h
#define function_h

void clear();
void pause();

#endif  
and define them in a source file.
1
2
3
4
5
6
7
8
9
void clear()
{
	system("cls");
}
void pause()
{
	char a;
	a=getch();
}


Or you can define them in the header if you define them as inline.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef function_h
#define function_h

inline void clear()
{
	system("cls");
}
inline void pause()
{
	char a;
	a=getch();
}

#endif  
You should make it so "functions.h" only contains the prototypes like so:

1
2
3
4
5
6
7
8
#ifndef function_h
#define function_h

void clear();

void pause();

#endif 


Then, you should make a "functions.cpp" that contains the implementations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//functions.cpp

#include "functions.h"

void clear()
{
   system("cls");
}

void pause()
{
   char a;
   a=getch();
}


This way, the implementations of these functions only appear in one "translation unit". The way you have it, the implementations appear both when compiling UserInterface.cpp and when compiling main.cpp.
Edit: Removed my third copy of essentially the same answer.
Last edited on
Topic archived. No new replies allowed.