How can i call (execute) a file (with ".c" extention) from the particular path without including it into main file ? Now the file which we have to call from particular path is containing only a function (without "main()").....

Dani AI

Generated

raised a common point: a bare .c that only defines a function cannot be "called" directly by the shell. and were right to steer the discussion toward building and linking. Practical choices that work today (and avoid the bad habit of #include "file.c") are:

Compile-and-link at build time (recommended)
Build the helper source to an object and link it with the main program. Provide the function prototype in a header the main program can include (or declare it extern), and use -I if the header lives in another folder.

gcc -c /path/to/helper.c -o helper.o
gcc main.c helper.o -o mainprog

Create a library (static or shared)
Turn the helper into a .a or .so and link by name. For shared libraries use -fPIC when compiling and set LD_LIBRARY_PATH or an rpath at runtime.

gcc -c /path/to/helper.c -fPIC -o helper.o
gcc -shared -o libhelper.so helper.o
gcc main.c -L/path/to -lhelper -o mainprog

Runtime dynamic loading
If the goal is truly "decide at runtime which module to use," compile a shared object and use dlopen/dlsym to obtain function pointers (platform differences on Windows require LoadLibrary).

Common troubleshooting
Undefined reference => object/library not passed to the linker. Mismatched prototypes => crashes or wrong behavior. For shared libs remember -fPIC and runtime loader paths. For details on compilers and dynamic loading see the GCC docs (https://gcc.gnu.org/onlinedocs/gcc/) and the dlopen manual (https://man7.org/linux/man-pages/man3/dlopen.3.html).

Recommended Answers

All 3 Replies

.c files do not get called in the shell to be interpreted, they need to be compiled, and then linked as part of a program.

.c files do not get called in the shell to be interpreted, they need to be compiled, and then linked as part of a program.

ya....ok so how to compile or that file from perticular place...

Add it to the compile command.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.