title: Running automated tests on several C files
body: <p>I have several files in the structure</p>
  
  <pre><code>/algorithms
      /a1
          a1.c
      /a2
          a2.c
      /a3
          a3.c
  </code></pre>
  
  <p>Each of these files contains a function of the same name. Each has the same signature, except for the name (which is the same as the filename). Essentially, each algorithm is a different implementation of the same thing -- different means to the same end. There may however be small helper functions.</p>
  
  <p>The content of the files (comments, functions, layout, etc) cannot change.
  I want to create some method that will test each algorithm. This method <em>is not</em> confined to being implemented in C.</p>
  
  <p>I have a C file that essentially contains three functions:</p>
  
  <pre class="lang-c prettyprint-override"><code>// Runs the algorithm, which modifies the given integer array.
  void run(void (*algorithm) (int*, size_t));
  
  // Checks that the algorithm successfully completed and
  // the array is correct.
  int check(int*, size_t);
  
  // Should call run() with appropriate algorithm and a random data set
  // and then call check() to make sure it worked.
  int main(int, char**);
  </code></pre>
  
  <p>I need an automated way of including the appropriate files and then calling
  the function within them. Currently, I have a bash file that gets all the algorithms, copies the tester file, prepends an <code>#include</code> statement at the beginning and a generated <code>injected_main()</code> function that gets called by the actual <code>main()</code> function. It runs the copied tester and then deletes it.</p>
  
  <pre class="lang-sh prettyprint-override"><code>function testC() {
  
      local tempout=temptest.c
      local filename="$(basename -- $1)"
      local functionname="${filename%.*}"
      local main="void injectedMain() {test(&amp;$functionname);}"
      local include="#include\"$1\"\n$main"
  
      touch $tempout
      chmod +x $tempout
      printf "$filename: "
      cp $TESTER_C $tempout
      printf "$include" &gt;&gt; $tempout
      gcc $tempout -o tempout -Wall -Wextra -pedantic
      ./tempout
      rm $tempout tempout
  
  }
  </code></pre>
  
  <p>Where the function is run in a loop for every algorithm C file.
  However, this method is prone to error, not extendable, and just downright ugly. Is there a better way to do this?</p>