Thread: using a shared lookup table

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    57

    using a shared lookup table

    Im having some problems setting up and using a shared lookup table between multiple files.

    At first I thought my problems were just because I forgot about using externs, now Im really not sure how you should go about it. I don't want to redefine it (with the values)in every file and you cant assign the values to it when you declare it. For my example the table is small but in my program its kind of big and messy.

    So to keep things simple, lets say you have main.c
    Code:
    #include "stuff.h"
    
    int main() {
    	foo(2);
    
    	return 0;
    }
    stuff.h
    Code:
    #ifndef _STUFF_H_
    #define _STUFF_H_
    
    int foo(int y);
    
    #endif
    stuff.c
    Code:
    #include "data.h"
    
    int foo(int y) {
    	return (2 * lookup_table[y]);
    }
    data.h
    Code:
    #ifndef _DATA_H_
    #define _DATA_H_
    
    int lookup_table[4] = {42, 43, 44, 45};
    
    int lookup(int x);
    
    #endif
    and data.c
    Code:
    #include "data.h"
    
    int lookup(int x) {
    	return lookup_table[x];
    }
    With this example I get these errors
    /usr/bin/ld: multiple definitions of symbol _lookup_table
    /var/tmp//ccu9bk8L.o definition of _lookup_table in section (__DATA,__data)
    /var/tmp//cc2RkuxQ.o definition of _lookup_table in section (__DATA,__data)
    collect2: ld returned 1 exit status
    So how should you go about this?
    Thanks

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    this
    Code:
    int lookup_table[4] = {42, 43, 44, 45};
    should go in one of c files

    This
    Code:
    extern int lookup_table[4];
    should go into header
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 02-06-2009, 12:27 PM
  2. search file for values in lookup table
    By sixstringsgaret in forum C Programming
    Replies: 12
    Last Post: 03-04-2008, 04:23 PM
  3. Lookup table with different spacing between entries
    By Boksha in forum C++ Programming
    Replies: 2
    Last Post: 02-19-2008, 02:40 PM
  4. Writing array, to file
    By zootreeves in forum C Programming
    Replies: 9
    Last Post: 09-08-2007, 05:06 PM
  5. Lookup Table Reference???
    By gvector1 in forum C++ Programming
    Replies: 3
    Last Post: 04-02-2003, 05:03 PM