Passing pointer to static global variable in C

旧街凉风 提交于 2019-12-23 12:12:50

问题


Is it safe to pass a pointer to a static struct to a function?

I have something like this:

mymodule.c:

static MYEVENT_STRUC_T event;
uint_32 _myRtos_set_event(MYEVENT_STRUCT_T* event_ptr, uint_32 mask);

uint_32 mymodule_set_event(uint_32 event_mask){   

    /* Kernel function */
    /* Defined outside mymodule.c,*/
    /* Is it safe to call it with &event?  */
    return _myRtos_set_event(&event, event_mask);

}

回答1:


It is safe. static doesn't mean "can't be used outside the module", but rather "can't be referenced outside the module", i.e. the symbol itself won't be exported, but the variable still exists somewhere in the memory of the process an can be used between modules as well.

The only thing I'm uncertain of is that I'm not sure it's safe to pass data from user-mode to kernel-mode via pointer, if that's what you're doing. If I recall correctly, there is some function you're supposed to call that copies memory from user-space to kernel-space. Not entirely sure, though.




回答2:


Please consider:

Preproccessor(*.h,*.hh , in newr version without suffix)>>>>>source files(*.c, *.cc *.cpp)>>>>Linker(*.o or *.obj , it's related to your compier)>>>>your output

According to above structure, you can't define a variable,array or something in source file. You should define your variable in header file as extern then use it in source file.



来源:https://stackoverflow.com/questions/22407964/passing-pointer-to-static-global-variable-in-c

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