Expose only required functions in C

有些话、适合烂在心里 提交于 2019-12-23 16:25:08

问题


I am writing a small API library sort of module in C. I will compile this module and give it to my fellow developers and I will expose some required functions in header file of my module so developers who will use my module know which function to call for required functionality. Now I want to inquire one thing: Can I expose only desired functions in C. e.g.

I have test.c having:

#include "test.h"
void A()
{
  if( some condition is true )
    B();
  else
   return;
}

void B()
{
  //some code here
}

and in test.h, I have only one function exposed i.e.

void A();

Now B() clearly is dependent on condition put in A() otherwise it can not be run and as only A() is exposed in test.h then user wont know that he/she can also directly call B(). Now my fear is that if user gets to know (or by guess) that there is some function in my module called B() which can be called directly by bypassing A(), then it can compromise my implementation.

I know that C++ would be better in this case because of public and private methods and I also have an idea that I can prevent B() being called directly by using some flag check of A() in B() but I want to know if there is any other method so that user cant call my functions (like B()) which are not exposed in header file.


回答1:


Make function B:

static void B(void)
{
  //some code here
}

Its visibility will be limited to the translation unit where it is defined. B will have internal linkage; A will have external linkage.




回答2:


Another kind of linkage that is only supported by gcc/clang on some *NIX is 'hidden' linkage.

You can define a function as such like so:

__attribute__((visibility, ("hidden"))) void foo(void) {
      return;
}

This will allow the function to be called from another point in the shared object but no point outside that. That is it could be called from a different translation unit but not from the app using your library.

See http://gcc.gnu.org/onlinedocs/gcc-4.4.1/gcc/Function-Attributes.html for more information.



来源:https://stackoverflow.com/questions/13174078/expose-only-required-functions-in-c

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