Memory allocation in header files

 ̄綄美尐妖づ 提交于 2020-01-15 11:55:06

问题


The company I'm working for have development rules for C development on embedded target. One is :

It is recommended to not allocate any storage space in the header files.

I'm not sure what it means, the person who wrote it is not around and the other developers don't really care, so I am asking here.

What I understand is that I shouldn't declare variables in a header files, so something like that would be discouraged in a .h :

   int myVar;
   static char myOtherVar;

What I don't understand is what's wrong with that ? Why shouldn't I do it ?


回答1:


What is wrong is that external variables get doubly defined, while static ones get defined for each module that includes the header, wasting space (unless they get optimized away).




回答2:


You should declare the variable in the C file, and use

extern int myVar;

in the header file, or better still, write an accessor function.

having static char myOtherVar; in the header makes no sense, since the static means it only accessible within the file where it is declared.



来源:https://stackoverflow.com/questions/22761174/memory-allocation-in-header-files

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