I am building a user defined shell where the shell dynamically links libraries
I have the following snippet from the main file that contains the global variable declarations...
char *prompt = "upsh";
int main()
{ ...
then I have a shared library as follows...
extern char *prompt;
int setprompt(char *argv[]) {
prompt = argv[1];
return 0;
}
my problem is that when I link the library from the main program I get the error
./setprompt.so: undefined symbol: prompt
...maybe this is a compilation issue?
As Naveem Kumar commented, you should provide compilation steps. Does the following reproduce what you meant? This worked in my laptop.
Makefile
all: main
libsetprompt.so: setprompt.c
gcc -fPIC -DPIC -shared setprompt.c -o libsetprompt.so
main: main.c libsetprompt.so
gcc main.c -o main -L. -lsetprompt
clean:
rm main libsetprompt.so
main.c
char *prompt = "upsh";
int main(int argc, char *argv[])
{ return 0; }
setprompt.c
extern char *prompt;
int setprompt(char *argv[])
{
prompt = argv[1];
return 0;
}
I do not think it is a comilation issue. If i get it right, you have a console application, which means that argc and argv must be passed to the main function in order to use them, but they are not passed. I guess your problem is that you call int setprompt(char *argv[]) without actually passing argv[]. But i may be wrong, more code would help to tell for sure.
But probably instead of int main() there should be int main(int argc, char **argv)
Related
I'm trying to find a method to, from a program, check the presence of one or more ".c" files and load one or more functions of it.
Basically, I would have a "main" program which will check if the "script.c" file exists, and will launch (if it exists) the main() function of this one.
Here is the content of my "main" program before compilation:
int main(int argc, char *argv[]){
...
if(argc == 1){
FILE *file;
if((file = fopen("script.c", "r"))){
printf("file script.c loaded.");
// to compile the script.c file and modify on it the "main()" function to "_main()" (in order to be able to recompile it with the main library) before restarting the program
int ret = system("gcc -c script.c && objcopy --redefine-sym main=_main script.o && gcc main script.o -o main && ./main -l script.o");
printf("ret(0)=%d\n", ret);
}
else{
int ret = system("./main -l");
printf("ret(1)=%d\n", ret);
}
}
else{
if(argc == 3 && strcmp(argv[2], "script.o") == 0){
_main(argc, argv);
}
else{
printf("no file found.\n");
}
}
...
}
He is the content of my "script.c" file:
int main(int argc, char *argv[]){
...
printf("main() function in script.c loaded.\n");
...
}
If the script.c file exists, running main should give:
file script.c loaded.
ret(0)=0
main() function in script.c loaded.
If the script.c file does not exist, running main should give:
file script.c loaded.
ret(1)=0
no file found.
Obviously, this does not work for several reasons.
It is impossible to use the "main" program to recompile the script.o file (especially since this is supposed to be in use)
It is impossible to compile my "main" program with a _main() function that does not exist (on the 1st launch, and potentially on the second too if script.c dont found)
Do you have an idea for me to achieve my goal ?
So from a single executable program (here "main") to be able to check the presence of an external file (here "script.c") and launch one or more functions from it...
PS: Having already seen it in other projects, I know it's possible, but I can't find the solution.
PS2: Only the executable file (main) and potentially the script.c file must be present (therefore no main.c...which therefore perhaps suggests that a "main" file should be merged with the "main.o" associated which would be unpacked and executed)
So from a single executable program (here "main") to be able to check the presence of an external file (here "script.c") and launch one or more functions from it...
I'm going to make an assumption that the main function you mentioned is not the most important and show how you can, from within your program, compile collections of functions into shared libraries that you load and then execute functions (other than main) in.
A simple driver could look like this:
// driver.c
#include <dlfcn.h> // to be able to dynamically load shared libraries
#include <stdio.h>
#include <stdlib.h>
// the signature of the `start` function you decide to have in all the files:
typedef void(*start_func_t)(void);
int main(int argc, char *argv[]){
char sys[1024];
for(int i = 1; i < argc; ++i) { // loop through all the arguments
// try to compile the argument into an object file
// (use a safer version than sprintf in real code)
sprintf(sys, "gcc -fPIC -c -o %s.o %s", argv[i], argv[i]);
if(system(sys)) {
printf("%d failed\n", sys);
exit(1);
}
// try to create a shared library from the object file
sprintf(sys, "gcc -shared -o libcurrent.so %s.o", argv[i]);
if(system(sys)) {
printf("%d failed\n", sys);
exit(1);
}
// load the shared library you just created
(void)dlerror();
void *handle = dlopen("./libcurrent.so", RTLD_NOW | RTLD_LOCAL);
if(!handle) {
puts(dlerror());
exit(1);
}
// lookup the "start" symbol in the shared library:
start_func_t start = dlsym(handle, "start");
if(!start) {
puts(dlerror());
exit(1);
}
// call the loaded function:
start();
dlclose(handle); // close the library
}
}
You need to link the above program with the dl library, so something like this should work:
gcc -o driver driver.c -ldl
Now, if you create some example files:
// t1.c
#include <stdio.h>
void start(void) { puts("Hello world"); }
// t2.c
#include <stdio.h>
void start(void) { puts("another file"); }
and then run:
./driver t1.c t2.c
It should produce this output if everything works out:
Hello world
another file
I also made a test to see how this works out if I put main in the library. That is, change the start_func_t signature to:
typedef int(*start_func_t)(int argc, char *argv[]);
and load and call main instead:
start_func_t start = dlsym(handle, "main");
if(!start) {
puts(dlerror());
exit(1);
}
// call the loaded function with some example arguments:
char *cargv[] = {
"foo", "hello", "world", NULL
};
start(3, cargv);
and change the test programs slightly:
// t1.c
#include <stdio.h>
int main(int argc, char *argv[]) {
for(int i = 0; i < argc; ++i) {
printf("t1: %s\n", argv[i]);
}
}
// t2.c
#include <stdio.h>
int main(int argc, char *argv[]) {
for(int i = 0; i < argc; ++i) {
printf("t2: %s\n", argv[i]);
}
}
and this worked fine too. However, main is a bit special and I'm not sure if this violates any rules.
I'm looking for an efficient (fast and secure) method to communicate multiple scripts (and their associated main function ()) to each other. A bit like the principle of the G-WAN project which uses a launcher (./gwan) to read / load / compile different .c files which each contain (or not) a main() function.
Ideally, my launcher should be able to execute the main () functions of other scripts while sharing information through their argv variables.
But as you know, gcc -Wall script1.c script2.c script3.c -o test return me an error of multiple definition of function main(), and gcc -Wl,--allow-multiple-definition -Wall script1.c script2.c script3.c -o test interprets only the first script1.c main() function.
Maybe the solution would be to have a first script (script1.c) which compiles the other scripts (script2.c and script3.c) via a shared variable?
Thanks for your help and sorry for my limited english.
script1.c:
int main(int argc, char *argv[]){
...
int i = main(argc, argv); // main for script2.c
if(i == 0)
main(argc, argv); // main for script3.c
...
return(0);
}
script2.c:
int main(int argc, char *argv[]){
...
return(0);
}
script3.c:
int main(int argc, char *argv[]){
...
return(0);
}
You can't have multiple main function in c, it's simply not allowed, what you can do is have your main function in your first .c file, and whatever you want in your others .c files.
Then you can write :
#include "script2.c"
#include "script3.c"
on top of your script1.c file.
If you want to compute values inside a file and "send" it to main file, you can do it through functions, defined in your other files, since you include it !
Notice that there is no scripts in C !
Let's say I have the following programs:
//gcc a_program.c -o a_program
void foo() {
printf("foo called\n");
}
int main(int argc, char** argv) {
execvp("some_other_program", argv);
}
//gcc some_other_program.c -o some_other_program
int main(int argc, char** argv) {
foo();
}
Is there a way to call foo from the new process image that execvp() creates? dlsym() only works on binaries loaded as dynamic libraries - according to the man page, at least - so I can't just search for the symbol in the new process, even if it exists.
No. When you exec a program the current process is completely replaced by the new one. Environmental factors like open file descriptors are retained, but code isn't. You can't call functions from the old process in the new one.
I've never used,
int main(int argc, const char * argv[])
For most programs, I usually just compile in terminal (using mac) using two separate C files, example…
gcc functions.c main.c
But now I need to use int main(int argc, const char * argv[])… I just don't know if I'm using it correctly. Heres some code…
I compile in the command line doing…
gcc main.c input.txt
terminal tells me…
ld: file too small for architecture x86_64
collect2: ld returned 1 exit status
NOTE my functions work (i tested without using file input) and are in main.c also… i just didn't include them in this post. Also, node is just a basic node struct to a linked list.
int main(int argc, const char * argv[])
{
FILE *input;
input = fopen(argv[1], "r");
node *list = malloc(sizeof(node));
char *string = malloc(sizeof(char)*1023);
fscanf(input, "%s", string);
//convert a string to linked list
list= sTol(string);
//print the linked list
printList(list);
return 0;
} // end main()
Am i completely wrong? the input simply contains one line that says 'hello'. All I'm trying to do is read that into my program and print it just to verify I'm reading my input correctly.
This is not like a perl script or shell script, where you run
perl main.pl input.txt
With a compiled language like C, you first compile the program into an executable
gcc main.c -o myprogram
and then run the executable with the input file
./myprogram input.txt
I am trying to use the 'environ' variable, but it keeps giving me an error. It seems to be a makefile/build error and I can't seem to fix it. I have searched fo answers, but still I am lost.
Here is my c file:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include "cmd.h"
int cmdExec() {
...
extern char **environ;
...
printf("Enter a command\n");
//gets (input);
scanf("%s%*[^\n]", input);
if (...) {
...
}
else if (strcmp(input, "environ") == 0) {
int i;
for (i = 0; environ[i] != NULL; i++) {
printf("%s\n", environ[i]);
}
exit(0);
else
...
return 0;
}
and here is the makefile:
CC = gcc
CFLAGS = -c
CFLAGS-y = -std=c99
all: cmd
cmd.o: cmd.c cmd.h
$(CC) $(CFLAGS) $(CFLAGS-y) cmd.c
cmd.exe: cmd.o
$(CC) -o cmd.exe cmd.o
clean:
rm -rf *.o cmd.exe a.out
This is the output:
make all
gcc -c -std=c99 cmd.c
gcc cmd.o -o cmd
cmd.o:cmd.c:(.text+0x105): undefined reference to `environ'
cmd.o:cmd.c:(.text+0x127): undefined reference to `environ'
collect2: ld returned 1 exit status
make: *** [cmd] Error 1
From what I've searched this deals with linking libraries, but I don't know how to apply that to my specific situation. If someone could give me a hand I'd appreciate it.
Not all(if any) compilers on Windows provides access to environment variables through a global symbol named environ.
You can use e.g. getenv() to access environment variables.
The win32 API provides GetEnvironmentStrings() to access all the variables.
Some platforms allow you to access the environment through an additional argument to main(), you'd declare your main function as:
int main(int argc, char *argv[], char *environ[])
The environ global variable is defined by POSIX, and is not supported by Windows (unless you're using Cygwin, which is a POSIX-like layer implemented on top of Windows).
As far as I know, the non-standard definition
int main(int argc, char **argv, char **envp) { /* ... */ }
is also not supported on Windows.
But a quick Google search turned up this answer, which points to the documentation for the Windows-specific GetEnvironmentStrings function:
LPTCH WINAPI GetEnvironmentStrings(void);
If the function succeeds, the return value is a pointer to the
environment block of the current process.
If the function fails, the return value is NULL.
The result points to a long string with the environment variables separated by '\0' null characters, with the environment terminated by two consecutive null characters.
LPTCH is Microsoft's typedef for a pointer to either unsigned char or a 16-bit wchar_t. See the referenced documentation for more information.