user2405854
user2405854

Reputation:

Link Multiple Declarations to Same Definition

I have implemented a linked list in C (not C++) that stores pointers to data. I would like to have multiple declarations for its functions (to provide type safety), but have each of them link to the same definition (because there is no actual difference between pointers to different data types, so using the same code reduces space).

Does anyone have any ideas on how to achieve this (or any better ways to do it)? A portable solution is obviously best, but I really just need something that works in GCC.

Upvotes: 3

Views: 161

Answers (3)

vvy
vvy

Reputation: 2073

#include <stdio.h>
struct common_type {
    int type;
};

struct type1 {
    int type;
    int value;
};

struct type2 {
    int type;
    char* p;
};

int func(void *para) {
    switch (((struct common_type*)para)->type) {
        case 1:
            printf("type1,value:%d\n",((struct type1*)para)->value);
            break;
        case 2:
            printf("type2,content:%s\n",((struct type2*)para)->p);
            break;
    }
}

int main() {
    char *s = "word";
    struct type1 t1 = {1,1};
    struct type2 t2;
    t2.type = 2;
    t2.p = s;
    func((void*)&t1);   
    func((void*)&t2);
}

Upvotes: 0

Anthony
Anthony

Reputation: 12397

I believe you might be able to achieve this using typedefs for function prototypes and casting the generic solution (which deals in void*s) to the specific prototype. This should be safe for compilation because all pointers would be the same size.

Consider this example:

do_something.h:

typedef void (*do_something_with_int_t)(int *i);
extern do_something_with_int_t do_something_with_int;

typedef void (*do_something_with_string_t)(char *s);
extern do_something_with_string_t do_something_with_string;

do_something.c

#include "do_something.h"

void do_something_generic(void* p) {
    // Do something generic with p
}


do_something_with_int_t do_something_with_int =
    (do_something_with_int_t)do_something_generic;

do_something_with_string_t do_something_with_string =
    (do_something_with_string_t)do_something_generic;

As long as do_something_generic is truly datatype-agnostic (i.e. it really doesn't matter what p points to) then this would be OK.

Upvotes: 1

Ziffusion
Ziffusion

Reputation: 8923

If it's C (not C++), then the following will work just fine. You can adapt the concept to your needs.

tt.h

typedef struct {
    int ii;
} Type_1;

typedef struct {
    int ii;
} Type_2;

int foo_1(Type_1* ptr) __attribute__((alias("foo")));
int foo_2(Type_2* ptr) __attribute__((alias("foo")));

tt.c

#include <stdio.h>

#include "tt.h"

int main() {
    Type_1 t_1;
    Type_2 t_2;
    foo_1(&t_1);
    foo_2(&t_2);
}   

int foo(void* arg) {
    printf("foo: %p\n", arg);
}

Upvotes: 0

Related Questions