title: How to initialize api function pointers from a dynamic library in a C-API
body: <p>I'm explicitly loading a c-API dynamic library (dll/so), where it is not possible to link symbols with a lib-file. So I use GetProcAddress and dlsym to find the apropriate functions.</p>
  <p>The problem I have is due to the static declaration of &quot;foo&quot; and &quot;baz&quot; I have to use GetProcAddress/dlsym for every implementation file that includes this header.</p>
  <p>The behaviour I want is that I only want to lookup the symbols once for the process.</p>
  <p>Do I have to declare them all as &quot;extern&quot; then have a own set of function pointers in the project that I then set with GetProcAddress/dlsym?</p>
  <p>What is the recommended way to fix it?</p>
  <p>Example API header:</p>
  <pre><code>#ifdef _WIN32
  #define API_IMPORT __declspec(dllimport)
  #define API_EXPORT __declspec(dllexport)
  #elif defined(__GNUC__)
  #define API_EXPORT __attribute__((visibility(&quot;default&quot;)))
  #define API_IMPORT
  #else
  #error Unsupported for now
  #endif
  
  #if LIB_COMPILING
  #define API_DECL API_EXPORT
  #else
  #define API_DECL API_IMPORT
  #endif
  
  #ifdef __cplusplus
  extern &quot;C&quot; {
  #endif
  
  API_DECL int ifoo(int bar);
  API_DECL void ibaz(int qux);
  typedef int (* PFN_FOO_PROC)(int);
  typedef void (* PFN_BAZ_PROC)(int);
  static PFN_FOO_PROC foo = 0;
  static PFN_BAZ_PROC baz = 0;
  
  #ifdef __cplusplus
  }
  #endif
  </code></pre>
  <p>&quot;ifoo&quot; and &quot;ibaz&quot; contains the actual implemenations in a c-file for the dynamic library.</p>
  <p>So in this example to load symbols for linux:</p>
  <pre><code>        foo = (PFN_FOO_PROC) dlsym(handle, &quot;ifoo&quot;);
          baz = (PFN_BAZ_PROC) dlsym(handle, &quot;ibaz&quot;);
  </code></pre>
  <p>Thanks for any help</p>