c - Error in accessing struct in some other file using extern -


i'm new c. reading extern.i used built-in data dypes , worked fine.when used structs, gave following error. doing wrong?

bar.c

struct myx {     int x; } x; 

foo.c

extern struct myx x; int main() {     x.x=80;     return 0; } 

gcc -o barfoo foo.c bar.c error: invalid use of undefined type 'struct myx'

 x.x=80;  ^ 

because gcc -o barfoo foo.c bar.c (which should gcc -wall -wextra -g foo.c bar.c -o barfoo; should enable warnings , debugging info when compiling code) compiling 2 compilation units (foo.c , bar.c) linking object files together.

every compilation unit (or translation unit) "self-sufficient" regarding c declarations; should declare every -non-predefined- type (e.g. struct) using in translation unit, in common header file.

so should have

struct myx {   int x; }; 

and

extern struct myx x; 

in both foo.c & bar.c. avoid copy-pasting, want put in myheader.h , use #include "myheader.h" @ start of both foo.c , bar.c, i.e. use

// file myheader.h #ifndef myheader_included #define myheader_included struct myx {   int x; }; extern struct myx x; #endif /* myheader_included */ 

notice conventional use of include guard. read more c preprocessor, e.g. documentation of gnu cpp.

some programming languages (e.g. ocaml, rust, go, ... not c, , not yet c++) have modules or packages deal issue.

ps. should study source code of free software coded in c. you'll learn lot.


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

xcode - Swift Playground - Files are not readable -

jboss7.x - JBoss AS 7.3 vs 7.4 and differences -