# How to link two programs written in C++?

Status
Not open for further replies.

#### shedeed

##### Member level 4
i want to know how to link two programs written in C++

#### Antharax

##### Full Member level 4

what do you mean with linking?

Do you mean you want a compiler to make 1 binary out of the sources?
In that case, just combine the sources (use only 1 main ;-) ) and compile.
(What OS, what compiler are you using???)

Otherwise pipes might be a possible solution but what exactly do you want to do?

Antharax

#### shedeed

##### Member level 4

i mean that i have a program written that have a certain functions it does, and i want to use these functions in another program without cpying them again.
i've once read that #include<filename> or the "#define" preprocessor can be used

#### JankoMuzyk

##### Member level 2

shedeed said:
i mean that i have a program written that have a certain functions it does, and i want to use these functions in another program without cpying them again.

if your program is excutable it's no possiblity to 'link' with another one.
You can only write static or dynamic library that can be linked with other programs.

shedeed said:
i've once read that #include<filename> or the "#define" preprocessor can be used
- it's not true

#### Antharax

##### Full Member level 4

ah yes,
Now i see what you mean.

Just make a header file for the c/cpp file you want to reuse

Code:
#ifndef foo1_h_
#define foo1_h_

int foo1(int argument);

#endif // foo1_h_

C-file foo1.c
Code:
#include "foo.h"

int foo(int argument)
{
return argument;
}

Explanation of lines in header file:
line 1, 2 and 5 (#ifndef ..., #define ..., #endif ...) are the well know guard statements in header files to avoid multiple inclusions. When a header file is included in a c or cpp file (by using #include "headerYouWant.h") everything is just copied in the c file by the preprocessor. This is also true for header files included in other header files. In this way it is possible that a header file (eg myTypes.h which you use to make your own typedefs) is included multiple times in a c or c++ file. This is a problem for typedefs!

When you want to reuse the foo code in your main:

Code:
#include "foo.h"

int main(void)
{
int result;

result = foo(100);
}

Antharax

Points: 2