Reputation: 53
I am currently learning the C programming language and I'm having some issues with importing modules I created.
I created a small module to read with fgets
and flush the buffer from stdin perfectly and I don't want to keep writing the code every single time. I just want to import this small module like I used to do in Python. I didn't knew how because I'm not using an IDE. I'm just compiling with gcc in terminal and using a text editor. I tried to search with Google,but in vain.
Upvotes: 1
Views: 3329
Reputation: 754090
You should create a header for your module that declares the functions in the module – and any other information that a consumer of the module needs. You might call that header weekly.h
, a pun on your name, but you can choose any name you like within reason.
You should create a library (shared or static — that's up to you) that contains the functions (and any global variables, if you're so gauche as to have any) defined by your module. You might call it libweekly.so
or libweekly.a
— or using the extensions appropriate to your machine (.dylib
and .a
on macOS, for example). The source files might or might not be weekly.c
— if there's more than one function, you'll probably have multiple source files, so they won't all be weekly.c
. You should put this code (the header and the source files and their makefile) into a separate source directory.
You should install the header(s) and the library in a well-known location (e.g. $HOME/include
for headers and $HOME/lib
for the library — or maybe in the corresponding directories under /usr/local
), and then ensure that the right options are used when compiling (-I$HOME/include
for the headers) or linking (-L$HOME/lib
and -lweekly
).
Your source code using the module would contain:
#include "weekly.h"
and your code would be available. With shared libraries in $HOME/lib
, you would have to ensure that the runtime system knows where to find the library. If you install it in /usr/local
, that is done for you already. If you install it in $HOME/lib
, you have to investigate things like /etc/ld.so.conf
or the LD_LIBRARY_PATH
or DYLIB_LIBRARY_PATH
environment variables, etc.
Upvotes: 1
Reputation: 67546
You need to create a header file (.h) with your function declarations types and extern variables. Then in the program where you want to use those functions include this .h file and and add the compiled .o file (with your functions) to the object file list. And you are done.
Upvotes: 0