简体   繁体   中英

Loading a c program in another one

I have written a program and i want to link it to another c program. In the sense, by using the include or any other directive, I need to link the programs, such that a function of the former can be called by the latter. How can i accomplish this in codebloacks ?

Suppose you have now two programs A and B. And in A you have function c . So, move c to separate file cc and make ch file, that can be included in both A and B program as #include "ch" . Than compile A and B independently.

It will be the simplest way.

EDIT:

All function that uses one another should be in the "library". Eg:

// c.h
int c(int x1, int x2); // this will be called from outside

extern int callCount; // to be available outside

and

// c.c
#include "c.h"

int d(int x); // this cannot be called from outside

// global variable to count calls of c function
int callCount = 0; 

int c(int x1, int x2)
{
    callCount++; // changing of global variable
    return (x1 + x2) * d(x1);
}

int d(int x)
{
    return x * x;
}

and usage

// prog A
#include <stdio.h>
#include "c.h"

int main(void) 
{
    int a = 1, b = 2;
    printf("c = %d\n", c(a, b));
    printf("c = %d\n", c(2*a, b - 1));
    printf("Function c was called %d times\n", callCount);
    return 0;
}

All the functions that you are planning to call from other files should be declared in h-file. It is the common approach, but also lots of tips can be find in the Internet, such as static functions, #define detectives and conditional compilation, etc.

It (loading a C program in another one) cannot be stricto sensu done, since there is only one single main function in any given program. However the system(3) & popen(3) functions enable you to start another program -thru a command line- from a first one. On Linux and POSIX systems you also can start a process using fork(2) and you can execute a program in a process using execve(2) . Of course this is operating system specific!

However, on some operating systems and platforms, you can use dynamic linking to load some plugin at runtime . The loaded plugin is not a program (it does not have any main function), but a library .

For example, on Linux and POSIX systems, you could use the dlopen function to load a plugin (often some shared library ), and the dlsym function to get a symbol inside it.

On Linux, dlopen is loading an ELF shared object which should contain position-independent code .

PS. You can also link a library (at build time) to your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM