C/C++ : exporting variable from a .h -
in c/c++, use main.cpp ready-to-use variable (mtab) :
- declared , initialized in lib.h
- implemented in lib.cpp
i can't make work : what's wrong ? seems typedef ignored , don't why ?
note :
- as mtab must same each user of lib.h, added static keyword
- as static variable must initialized (to avoid unexpected behavior), initialized mtab in lib.h
- when move mtab initialisation in lib.cpp : compilation ko
- when move mtab declaration , initialisation in lib.cpp, and, use "extern" in main.cpp : compilation ko
- the way compilation ok put mtab declaration , initialisation inside main scope in main.cpp... not want ! (inside main scope compilation ok. outside main scope, @ include level, compilation ko)
thanks help,
fh
~>more * lib.cpp
#include "lib.h" void m1 ( unsigned int const idatasize, int * const iopdata ) { return; } void m2 ( unsigned int const idatasize, int * const iopdata ) { return; } lib.h
#ifndef __lib__ #define __lib__ void m1 ( unsigned int const idatasize, int * const iopdata ); void m2 ( unsigned int const idatasize, int * const iopdata ); typedef void ( *pf ) ( unsigned int const idatasize, int * const iopdata ); static pf mtab[2]; // ready-to-use variable exported mtab[0] = &m1; mtab[1] = &m2; #endif main.cpp
#include "lib.h" #include <stddef.h> // null int main () { (*mtab[0]) ( 0, null ); (*mtab[1]) ( 0, null ); return 0; } makefile
all: gcc -i. -c lib.cpp -o lib.o gcc -i. -c main.cpp -o main.o gcc -i. lib.o main.o -o main.exe console:
~>make gcc -i. -c lib.cpp -o lib.o in file included lib.cpp:1:0: lib.h:7:1: error: ‘mtab’ not name type lib.h:8:1: error: ‘mtab’ not name type make: *** [all] error 1
first, put declarations, not definitions of objects or functions, in shared header files. mtab, use in lib.h:
extern pf mtab[2]; second, define object in 1 , 1 source file. put in lib.cpp:
pf mtab[2] = { m1, m2 }; third, mtab[0] = &m1; not initialization of mtab. assignment statement, in wrong place, because cannot have assignment statements @ file scope. proper way initialize mtab shown above. (assignments different initializations. assignments executable statements , must inside function bodies. initialization part of creation of object, may happen prior primary execution of program.)
fourth, static not make object same each user. has 2 effects, may vary depending on used. when used @ file scope, says identifier has internal linkage, means identifier refers only object in current compilation; not linked externally same identifier in other compilations. means opposite of wrote; means each source file has own mtab, not share 1 mtab. (the second effect of static static give object static storage duration, lifetime entire execution of program. however, has no effect @ file scope because object declared @ file scope has static storage duration default.)
Comments
Post a Comment