title: Is there a better way to load a dll in C++?
body: <p>Right now I do something like this and it seems messy if I end having a lot of functions I want to reference in my DLL. Is there a better and cleaner way of accessing the functions without having to create a typedef for each function definition so that it will compile and load the function properly. I mean the function definitions are already in the .h file and I shouldn't have to redeclare them after I load the function (or do I?) Is there a better solution than using LoadLibary? I don't necessarily need that function if there is a way I can do the same thing within Visual Studio 2005 project settings.</p>
  
  <hr>
  
  <h2>BHannan_Test_Class.h</h2>
  
  <pre><code>#include "stdafx.h"
  #include &lt;windows.h&gt;
  
  #ifndef BHANNAN_TEST_CLASS_H_
  #define BHANNAN_TEST_CLASS_H_
  
  extern "C" {
  
      // Returns n! (the factorial of n).  For negative n, n! is defined to be 1.
      int __declspec (dllexport) Factorial(int n);
  
      // Returns true iff n is a prime number.
      bool __declspec (dllexport) IsPrime(int n);
  
  }
  
  #endif  // BHANNAN_TEST_CLASS_H_
  </code></pre>
  
  <hr>
  
  <h2>BHannan_Test_Class.cpp</h2>
  
  <pre><code>#include "stdafx.h"
  #include "BHannan_Test_Class.h"
  
  // Returns n! (the factorial of n).  For negative n, n! is defined to be 1.
  int Factorial(int n) {
    int result = 1;
    for (int i = 1; i &lt;= n; i++) {
      result *= i;
    }
  
    return result;
  }
  
  // Returns true iff n is a prime number.
  bool IsPrime(int n) {
    // Trivial case 1: small numbers
    if (n &lt;= 1) return false;
  
    // Trivial case 2: even numbers
    if (n % 2 == 0) return n == 2;
  
    // Now, we have that n is odd and n &gt;= 3.
  
    // Try to divide n by every odd number i, starting from 3
    for (int i = 3; ; i += 2) {
      // We only have to try i up to the squre root of n
      if (i &gt; n/i) break;
  
      // Now, we have i &lt;= n/i &lt; n.
      // If n is divisible by i, n is not prime.
      if (n % i == 0) return false;
    }
  
    // n has no integer factor in the range (1, n), and thus is prime.
    return true;
  }
  </code></pre>
  
  <hr>
  
  <h2>dll_test.cpp</h2>
  
  <pre><code>#include &lt;BHannan_Test_Class.h&gt;
  
  typedef int (*FactorialPtr) (int);
  FactorialPtr myFactorial=NULL;
  
  // Tests factorial of negative numbers.
  TEST(FactorialTest, Negative) {
  
      HMODULE myDLL = LoadLibrary("BHannan_Sample_DLL.dll");
  
      if(myDLL) {
          myFactorial = (FactorialPtr) GetProcAddress(myDLL,"Factorial");
  
          if(myFactorial)
          {
              EXPECT_EQ(1, myFactorial(-5));
              EXPECT_EQ(1, myFactorial(-1));
              EXPECT_TRUE(myFactorial(-10) &gt; 0);
          }
  
          FreeLibrary(myDLL);
      }
  
  }
  </code></pre>