strdup() function

前端 未结 7 1307
孤城傲影
孤城傲影 2020-12-02 00:01

I recently became aware that the strdup() function I\'ve enjoyed using so much on OS X is not part of ANSI C, but part of POSIX. I don\'t want to rewrite all my

7条回答
  •  一整个雨季
    2020-12-02 00:09

    a) What happens when I write my own function with the same name as a built-in function?

    You cannot re-define a function that already exists in a header file you are including. This will result in a compilation error.

    b) What can I do to avoid bad things happening to me on platforms that don't have strdup() without rewriting all my code to not use strdup(), which is just a bit tedious?

    I would recommend creating your own wrapper function to strdup, and replacing all your calls to use the new wrapper function. For example:

    char *StringDuplicate(const char *s1)
    {
    #ifdef POSIX
        return strdup(s1);
    #else
        /* Insert your own code here */
    #endif
    }
    

    Changing all your calls from strdup to StringDuplicate() should be a simple find-and-replace operation, making it a feasible approach. The platform-specific logic will then be kept in a single location rather than being scattered throughout your codebase.

提交回复
热议问题