Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share variable between libraries and program

I have 2 shared libraries(let them be 1.so,2.so) and program(a.out). 2.so is linked to 1.so and a.out - it has some functions that is used in 1 and a.

The code of 2.so is

FILE *in;
char filename[128];
int func_printer(int a)
{
    if(strlen(filename)==0)
    {
       sprintf(filename,"%ld",time(NULL);
    }
    if((in=fopen(filename,"a"))==NULL)return;
    fprintf(in,"%i",a);
    fclose(in);
}

a.out has next

extern int func_printer(int);
extern void some_action();
int main()
{
    some_action();
    func_printer(2);
    return 0;
}

And finally 1.so has method some_action

extern int func_printer(int);
void some_action()
{ 
    func_printer(1);
    printf("hello world");
    return;
}

So when a.out starts, it call's 1.so(some_action()) and it call's 2.so(func_printer). It create file with name of timestamp(t1), write in it some info. After that 1.so calls 2.so(func_printer) and it creates another file's with timestamp.

Is it possible in this situation that some_action write always to t1, but when program starts again it should write to another file. All in all simply when program starts all libraries should know the filename where to write(without hard predifining the file name like char *filename="somefile.txt";)?

like image 509
John Square Avatar asked Mar 25 '26 13:03

John Square


1 Answers

It seems like the only thing that writes to a file is 2.so. Just expose a setter:

char filename[128];

void set_filename(char * path) {
    strncpy(filename, sizeof(filename), path);
    filename[sizeof(filename) - 1] = '\0';
}

int func_printer(int a)
{
    FILE *in;
    if(strlen(filename)==0) {
       sprintf(filename,"%ld",time(NULL);
    }
    if((in=fopen(filename,"a"))==NULL)return;
    fprintf(in,"%i",a);
    fclose(in);
}
like image 121
willglynn Avatar answered Mar 28 '26 01:03

willglynn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!