0

What I would like to have is something like that :

./client.out:functionC.c:78: Error blabla <--- Here is my problem

./client.out:client.c:98: Error blabla

Here are my sample functions

/* client.c */
int main(int argc, char *argv[]) {
    
    if(functionCalled() == -1){
        fprintf(stderr, "%s:%s:%d: Error blabla\n", argv[0], __FILE__, __LINE__);
    }
    return 0;
} 

/* functionC.c */
int functionCalled(){
    fprintf(stderr, "%s:%s:%d: Error blabla\n", ?????, __FILE__, __LINE__);
    return -1;
}

Obviously I can't send the main.c name through the parameters. Do you think it is possible to get the mother program which calls the function ? I have a client and a server calling the same function but in case of error I need to know which program (client or server) crashed.

ANSWER :

Using : extern char *progName; in the functionC.c and char *progName; in client.c

Community
  • 1
  • 1
Hearner
  • 2,711
  • 3
  • 17
  • 34
  • I don't want to get the function which caused the problem but the `mainProgram.out:program.c:line` – Hearner Feb 23 '17 at 17:47
  • 2
    why can't you pass argv[0] to your function? it's a variable like any other – Chris Turner Feb 23 '17 at 17:49
  • @Jean-FrançoisFabre I tried your __PRETTY_FUNCTION__ and the answer you gave but it doesn't return what I needed. I edited my post you'll understand – Hearner Feb 23 '17 at 17:49
  • @ChrisTurner because in my application I am not able to put what I want through the function – Hearner Feb 23 '17 at 17:49
  • Not sure if I understand correctly, but if you want display command name, simply create static/global variable and init it in main. Something like `char* progName = NULL; int main(...) { progName=argv[0]; ...}` – ttdado Feb 23 '17 at 17:51
  • @Hearner copy it into a global variable then – Chris Turner Feb 23 '17 at 17:52
  • In fact, I can't change the `functionC.h` file so I can't put what I want in my functions or use global variables. There isn't something like __FILE__ that does it, it seems – Hearner Feb 23 '17 at 17:58
  • No, there is no preprocessor macro that expands to the value of `argv[0]`. There cannot be, because that value is not known until runtime. – John Bollinger Feb 23 '17 at 18:22

1 Answers1

1

Yes, you could do that in your main.c file:

static const char *executable = NULL;

const char *get_main_file()
{
    return executable == NULL ? "????" : executable;
}

in the main:

int main(...)
{
    executable = argv[0];
    ...

and call that get_main_file() from your other files. That way, argv[0] value is exported everywhere (maybe you want to do cosmetic changes on it, rework it to remove the full path, which can be done rather easily by adding the offset of the last path separator to executable if found, like basename does)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219