title: C - properly partitioning the code into multiple files
body: <p>I'm writing a program in C and I'm separating the parts in different .c files (modules).</p>
  
  <p>Some modules (say B and C) include the same module (say A) and when these modules (B and C) are included by another module (say D), a diamond "hierarchy" is formed that causes redefinition problems.</p>
  
  <p>Eg.</p>
  
  <p><strong>vec3.c</strong></p>
  
  <pre><code>#include &lt;math.h&gt;
  
  typedef struct {
      float x, y, z;
  } vec3;
  
  float dot(vec3 v1, vec3 v2) {
      return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
  }
  
  /* ... other stuff ... */
  </code></pre>
  
  <p><strong>ray.c</strong></p>
  
  <pre><code>#include "vec3.c"
  
  typedef struct {
      vec3 A, B;
  } ray;
  
  vec3 origin(ray r) {
      return r.A;
  }
  
  /* ... other stuff ... */
  </code></pre>
  
  <p><strong>sphere.c</strong></p>
  
  <pre><code>#include "ray.c"
  
  typedef struct {
      float t;
      vec3 p;
      vec3 n;
  } record;
  
  typedef struct {
      vec3 center;
      float radius;
  } sphere;
  
  typedef enum {false, true} bool;
  
  bool hit_sphere(sphere s, ray r, float tmin, float tmax, record *rec) {
      /* ... do stuff ... */
  }
  
  /* ... other stuff ... */
  </code></pre>
  
  <p><strong>camera.c</strong></p>
  
  <pre><code>#include "ray.c"
  
  typedef struct {
      vec3 origin;
      vec3 lower_left_corner;
      vec3 horizontal;
      vec3 vertical;
  } camera;
  
  /* ... other stuff ... */
  
  vec3 origin = {0.0, 0.0, 0.0};
  vec3 lower_left_corner = {-2.0, -1.0, -1.0};
  vec3 horizontal = {4.0, 0.0, 0.0};
  vec3 vertical = {0.0, 2.0, 0.0};
  
  camera cam = {origin, lower_left_corner, horizontal, vertical};
  </code></pre>
  
  <p><strong>main.c</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;float.h&gt;
  #include "sphere.c"
  #include "camera.c"
  
  /* ... other stuff ... */
  
  int main() {
      /* ... do stuff ... */
  }
  </code></pre>
  
  <p>In this case the problem arises because both camera.c and sphere.c include ray.c (and hence also vec3.c), so there is a double definition of the structures and functions defined in these modules.</p>
  
  <p>How can I rearrange the code to not have these problems?</p>
  
  <p>Thanks!</p>