duplicate symbol error in C

半腔热情 提交于 2019-12-01 23:52:38

I always thought declaring it in the header is the way to go.

Yes, it is. Declaring it in the header is fine. It is not any good to define it in a header, though. (unless it's static inline, but you probably don't want to do that these days.)

You should never have things in a header that require memory in the running program. This is a rough way of specifying it, but it works pretty well in practice.

In other words, the header should only have the prototype for the function, which is a compile-time thing that doesn't "exist" in the running program (unlike the code of the function itself, which of course exists at runtime):

void empty(float *array, int l);

Then put the code in a separate C file, which you compile and link separately.

You have the function empty defined as a global symbol in the header. This means it will be a visible symbol in all compilation units that include it. There are three general workarounds:

  1. make it a static function

    static void empty(...) {...}
    
  2. put the implementation into a separate compilation unit

    in header.h:

    void empty(float *array, int l);
    

    in empty.c implement it

  3. instruct your linker to ignore duplicate symbols. This differs from linker to linker, consult man ld.

    On OS X: -m flag.

    On Linux: -z muldefs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!