Overriding C library functions, calling original

后端 未结 4 1254
野性不改
野性不改 2020-12-03 11:00

I am a bit puzzled on how and why this code works as it does. I have not actually encountered this in any project I\'ve worked on, and I have not even thought of doing it my

4条回答
  •  离开以前
    2020-12-03 11:47

    What is happening here is that you are relying on the behaviour of the linker. The linker finds your implementation of getline before it sees the version in the standard library, so it links to your routine. So in effect you are overriding the function via the mechanism of link order. Of course other linkers may behave differently, and I believe the gcc linker may even complain about duplicate symbols if you specify appropriate command line switches.

    In order to be able to call both your custom routine and the library routine you would typically resort to macros, e.g.

    #ifdef OVERRIDE_GETLINE
    #define GETLINE(l, n, s) my_getline(l, n, s)
    #else
    #define GETLINE(l, n, s) getline(l, n, s)
    #endif
    
    #ifdef OVERRIDE_GETLINE
    ssize_t my_getline(char **lineptr, size_t *n, FILE *stream)
    {
       // ...
       return getline(lineptr, n, stream);
    }
    #endif
    

    Note that this requires your code to call getline as GETLINE, which is rather ugly.

提交回复
热议问题