Multiple instances of main method in C - c

I've got an issue with an assignment, but I'm not asking for help to do the assignment, just single problem.
My code is like this:
#include "linux/kernel.h"
#include "linux/unistd.h"
#include <linux/slab.h>
typedef _msg_t msg_t;
struct msg_t { /* members here */ };
static msg_t *bottom = NULL;
static msg_t *top = NULL;
int function_one (argA, argB) {
/* function is working, no need to show code*/
}
int function_two (argA, argB) {
/* function is working, so no need I guess to show the code*/
}
int main(int argc, char ** argv) {
char *in = "This is a testing message";
char msg[50];
int mlen;
function_one(in, strlen(in)+1);
mlen = function_two(msg, 50);
}
Here's the problem: When I do the make command from the directory, I get the error
/home/<username hidden by me>/dm510/linux-3.18.2/arch/um/os-linux/main.c:118:
multipli definition of 'main'
arch/um/kernel/built-in.o:
/home/<username hidden again>/dm510/linux-3.18.2/arch/um/kernel/file_i_created.c:60
first defined here"
What does this error mean? I only defined the main method one time in my own file

The message says you have (at least) two C files, main.c and file_i_created.c that are included in the build. Both have main() functions. (In C, the term is "function", not "method".) Remove one of those source files, or remove/rename the main() function in one of them.

You have multiple approaches here:
Usually there is only one main in a program. If so, decide, which is the actual main and rename the other one
If both mains are essential, you could try putting them in seperate namespaces
Really can't tell without seeing the file_i_created.c code though. Could be something else as well.

Related

Is it possible to call functions from arrays in C? [duplicate]

This question already has answers here:
How can I use an array of function pointers?
(12 answers)
Closed 4 years ago.
When I was making my terminal i was wondering if I can call a function by array.
(This code is not done yet so please code is a bit messy.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <unistd.h>
#include <limits.h>
#define true 1
#define false 0
typedef int bool;
/* Static */
static char Input[CHAR_MAX];
static char CurrentDirectory[CHAR_MAX];
static char *Command;
static char *Argument;
static char *Commands[]={"test","test2"};
/* Functions */
int Check_Command();
int test();
int test2();
/* --------- */
int main(){
printf("#######################\n\tterminal\n\tType \"help\" for the list of commands\n#######################\n");
prompt:
printf(">");
fgets(Input,CHAR_MAX,stdin);
int res=Check_Command();
if(res==0){printf("Unknown Command!\n");}
goto prompt;
}
/* Check_Command() function returns 0 if doesn't suceed and returns 1 of it suceeds */
int Check_Command(){
//Since input variable is static, no need to send in arguments
Input[strcspn(Input,"\r\n")]=0;
Command=strtok(Input," ");
Argument=strtok(NULL," ");
int x=0;
while(x<sizeof(Commands)){
if(strcmp(Command,Commands[x])==0){
Commands[x](); <----- Can I call a function like this?
return 1;
}
x++;
}
return 0;
}
/* Commands */
int test(){
printf("Success!\n");
getchar();
exit(0);
}
int test2(){
print("Success [2] \n");
getchar();
exit(0);
}
If this possible then this would be lit, Im too lazy to make commands into a executable and using if statements for all commands.
if you are too lazy to read the whole code here is a basic concept (UNTESTED):
static *Commands[]={"test","test2"};
int main(){
char *Command="test";
int x=0;
while(x<sizeof(Commands)){
if(strcmp(Command,Commands)==0){
Commands[x]();
}
x++
}
}
int test(){
printf("Hi");
}
int test2(){
printf("hey");
}
Edit:
static char Commands[]={test,test2}; DOES NOT WORK
This also includes the "possible duplicate" answer. (Im using Mingw, Windows 10)
It appears that you want to be able to take in a string such as test2 from the user, and then invoke the function test2(). There are two main ways you can approach this:
Homebrew structure mapping names to function pointers.
Using 'dynamic library loading' and function name resolution.
Array of structures
For the first, you define a structure such as:
struct FuncName
{
const char *name;
int (*function)(void);
};
And you can then define an array of these:
struct FuncName functions[] =
{
{ "test", test },
{ "test2", test2 },
};
enum { NUM_FUNCTIONS = sizeof(functions) / sizeof(functions[0]) };
When you get a name from the user, you can search through the array of names and find the matching function pointer to call.
int invoke_function(const char *name)
{
for (int i = 0; i < NUM_FUNCTIONS; i++)
{
if (strcmp(name, functions[i].name) == 0)
{
return (*functions[i].function)();
// Or just: return functions[i].function();
}
}
return -1; // No match found
}
This works reliably on all systems, but the demerit is that you must create the table of function pointers when you compile the program.
Dynamic library
The alternative is to use functions dlopen() and dlsym() from the <dlsym.h> header on Unix (POSIX) systems, or the equivalent on Windows.
Normally, you expect to find the functions in dynamically loaded libraries loaded with dlopen(), but there's usually a way to search the main executable for the names instead (pass a null pointer as the file name to dlopen() on POSIX systems). You can then call dlsym() to get the function pointer corresponding to the name you specify, which you can call.
void *dlh = dlopen(NULL, RTLD_NOW);
int (*funcptr)(void) = (int (*)(void))dlsym("test", dlh);
return (*funcptr)();
This omits error checking and you need the cast to convert from an object pointer (void *) to a function pointer because the C standard does not require that to be doable, but POSIX does (see the specification of
dlsym() already linked to).
Non-uniform function signatures
With both solutions, life is easy if all the callable functions have the same interface. Life is much messier if the different functions have different interfaces (so some expect no arguments, some expect one, some expect two, and the types of the arguments vary between functions, as do the return types). Expect to use lots of casts and be prepared to bludgeon the compiler into submission — isolate the code from everything else so as to leave the non-portable part well separated from the main code.
Beware: no compiler was consulted about the validity of any of this code!

Can anyone explain a misunderstanding with functions?

I want to understand why we write this DWORD MyExceptionHandler(void);
and this int foo(char *buf);, two times in this example.
Why we just write those functions without writing the definition:
DWORD MyExceptionHandler(void);
int foo(char *buf);
Example:
#include <windows.h>
#include <stdio.h>
DWORD MyExceptionHandler(void);
int foo(char *buf);
int main(int argc, char *argv[])
{
HMODULE l;
l = LoadLibrary("msvcrt.dll");
l = LoadLibrary("netapi32.dll");
printf("\n\nHeapoverflow program.\n");
if(argc != 2)
return printf("ARGS!");
foo(argv[1]);
return 0;
}
DWORD MyExceptionHandler(void)
{
printf("In exception handler....");
ExitProcess(1);
return 0;
}
int foo(char *buf)
{
HLOCAL h1 = 0, h2 = 0;
HANDLE hp;
__try{
hp = HeapCreate(0,0x1000,0x10000);
if(!hp){
return printf("Failed to create heap.\n");
}
h1 = HeapAlloc(hp,HEAP_ZERO_MEMORY,260);
printf("HEAP: %.8X %.8X\n",h1,&h1);
// Heap Overflow occurs here:
strcpy(h1,buf);
// This second call to HeapAlloc() is when we gain control
h2 = HeapAlloc(hp,HEAP_ZERO_MEMORY,260);
printf("hello");
}
__except(MyExceptionHandler())
{
printf("oops...");
}
return 0;
}
A function has to be declared before you can call it. There are two ways to do it:
You can put the entire function definition before the definitions of any functions that call it. The definition serves as a declaration as well.
You can put a prototype of the function before the definitions of any functions that call it. This simply declares the function's parameter and return types. The definition can be put later, or even in another compilation unit that you link with later.
Many programmers like to put prototypes of all their functions at the beginning of the file. This allows them to put the definitions in any order, rather than keeping track of which calls which so you can get all the dependencies right. In particular, it allows you to put the main() function first, which can make it easier to follow the logic of the program.

Pass command line argument to a sub function

I have a C program main routine which calls heirarchically several levels of functions. Eg :
main -> MyFunc -> MySubFunc -> MySub2Func
and I have a condition in MySub2Func which needs to be checked against a command line argument. Eg:
if (myvar == argv[1])
Other than passing argv as a parameter to subfunction , is there any other way I could acheive this. (because I need to do this in several functions lying at different heirarchical levels)
Each of the sub-functions lie in different C files. My aim is to perform a debug by temporarily checking a particular local variable against a cmd line argument (and taking further actions accordingly) .. hence modifying the entire heirarchy is unfortunately not desirable for my purpose.
[update from comment]
sorry that I forgot to mention .. i am trying to perform a debug by temporarily checking a particular local variable against a cmd line argument (and taking further actions accordingly) .. hence modifying the entire heirarchy is unfortunately not desirable for my purpose ..
The common approach is to "decouple" the two; the functions further down the call tree really shouldn't care or know about main()'s arguments, i.e. the command argument vector itself.
Instead, it should be abstracted into application-specific options, which are passed from main(), which parses the options out of the command line arguments, down to all application-specific functions that need them.
You might use global variables that are set in the main() function:
int g_argc;
char **g_argv;
int main(int argc, char **argv) {
g_argc = argc;
g_argv = argv;
MyFunc();
}
...
void MyFunc() {
MySubFunc();
}
...
void MySubFunc() {
MySub2Func();
}
...
void MySub2Func() {
if (myvar == g_argv[1]) {
do_the_thing();
}
}
As unwind said, the functions further down the chain should really not know anything about main's arguments. You should parse the command line arguments once setting the program's configuration. Additionally you should provide query functions for this configuration e.g.
/* --- config.c */
typedef struct {
int debug_enabled;
} config_t;
static config_t configuration;
int debug_enabled() {
return configuration->debug_enabled;
}
void initialize_config() {
/* set default parameters */
}
int set_config_from_cmd(int argc, char** argv){
/* parse CMD parameters and set config */
}
/* --- main.c */
int main(int argc, char** argv)
{
initialize_config();
if ( set_config_from_cmd(argc, argv) == -1 ) {
exit(-1);
}
/* do stuff, call functions */
}
int myfunction() {
if ( debug_enabled() ) {
printf("debug!");
}
/* do stuff */
}
Notice that I put the configuration related stuff into a separate file in order to hide the internals of the configuration structure. Only the interface e.g. debug_enabled() etc is exposed.
[for debugging]
Put this in a header included by all modules involved:
extern int g_argc;
extern char ** g_argv;
Define g_argc and g_argv globally in the main module
int g_argc = 0;
char ** g_argv = NULL;
Then in main() just do
int main(int argv, char ** argv)
{
g_argc = argc;
g_argv = argv;
and access g_argc and g_argv from the modules in question.

Implementing callbacks between files in C

My program contains the following files: data_handler.c, app.c and callback_struct.h.
data_handler.c retrieves data from functions in app.c, by making callbacks to app.c.
The program should allow the user to define a set of functions with arbitrary names in app.c. The user does this by defining his functions, and associating them with a set of initiated function pointers (ptr_func1, ptr_func2 etc.), found in callback_struct.h.
With this approach I want to eliminate the need of making explicit calls from data_handler.c to the user functions in app.c (so that the code in data_handler.c do not have to be modified if the user changes his function names for example), neither do I want to have to include (#) app.c into data_handler.c.
Clearly there is something I'm not getting here. I would be grateful if someone could help me understand what I'm doing wrong, and perhaps give me some indications on whether or not I'm on the right track with my suggested implementation
See my implementation below:
callback_struct.h:
struct callback_struct{
int (*ptr_func1)(void);
int (*ptr_func2)(void);
// etc...
};
extern struct callback_struct user_functions; // should be defined in app.c
app.c
#include "callback_struct.h"
int user_function_func1(void);
int user_function_func2(void);
struct callback_struct user_functions={
.ptr_func1 = user_function_func1,
.ptr_func2 = user_function_func2,
};
int user_function_func1(void){
int data = 1; // for example...
return data;
}
int user_function_func2(void){
int data = 2; // for example...
return data;
}
// etc.....
data_handler.c
#include "callback_struct.h"
/*this function makes callbacks to app.c to retrieve data*/
void get_data(int (*ptr)(void)){
int retrieved_data=ptr();
}
void main(void){
get_data(user_functions.ptr_func1);
get_data(user_functions.ptr_func2);
// etc....
}
It's only a syntax error. Just replace
extern struct user_functions={
by
struct callback_struct user_functions={
in your app.c and it will work.
When you declare a global variable 'extern', you are telling the compiler that this variable is instantiated (and possibly initialized) somewhere else in the code.
Therefore, you should not declare it 'extern' and initialize it in the same line, which is exactly what you did in file app.c.

How do I write a dispatcher, if my compiler's support for pointers-to-functions is broken?

I am working on an embedded application where the device is controlled through a command interface. I mocked the command dispatcher in VC and had it working to my satisfaction; but when I then moved the code over to the embedded environment, I found out that the compiler has a broken implementation of pointer-to-func's.
Here's how I originally implemented the code (in VC):
/* Relevant parts of header file */
typedef struct command {
const char *code;
void *set_dispatcher;
void *get_dispatcher;
const char *_description;
} command_t;
#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label, &set_##dispatcher, &get_##dispatcher, (const char*)description}
/* Dispatcher data structure in the C file */
const command_t commands[] = {
COMMAND_ENTRY("DH", Dhcp, "DHCP (0=off, 1=on)"),
COMMAND_ENTRY("IP", Ip, "IP Address (192.168.1.205)"),
COMMAND_ENTRY("SM", Subnet, "Subunet Mask (255.255.255.0)"),
COMMAND_ENTRY("DR", DefaultRoute, "Default router (192.168.1.1)"),
COMMAND_ENTRY("UN", Username, "Web username"),
COMMAND_ENTRY("PW", Password, "Web password"),
...
}
/* After matching the received command string to the command "label", the command is dispatched */
if (pc->isGetter)
return ((get_fn_t)(commands[i].get_dispatcher))(pc);
else
return ((set_fn_t)(commands[i].set_dispatcher))(pc);
}
Without the use of function pointers, it seems like my only hope is to use switch()/case statements to call functions. But I'd like to avoid having to manually maintain a large switch() statement.
What I was thinking of doing is moving all the COMMAND_ENTRY lines into a separate include file. Then wraps that include file with varying #define and #undefines. Something like:
/* Create enum's labels */
#define COMMAND_ENTRY(label,dispatcher,description) SET_##dispatcher, GET_##dispatcher
typedef enum command_labels = {
#include "entries.cinc"
DUMMY_ENUM_ENTRY} command_labels_t;
#undefine COMMAND_ENTRY
/* Create command mapping table */
#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label, SET_##dispatcher, GET_##dispatcher, (const char*)description}
const command_t commands[] = {
#include "entries.cinc"
NULL /* dummy */ };
#undefine COMMAND_ENTRY
/*...*/
int command_dispatcher(command_labels_t dispatcher_id) {
/* Create dispatcher switch statement */
#define COMMAND_ENTRY(label,dispatcher,description) case SET_##dispatcher: return set_##dispatcher(pc); case GET_##dispatcher: return get_##dispatcher(pc);
switch(dispatcher_id) {
#include "entries.cinc"
default:
return NOT_FOUND;
}
#undefine COMMAND_ENTRY
}
Does anyone see a better way to handle this situation? Sadly, 'get another compiler' is not a viable option. :(
--- Edit to add:
Just to clarify, the particular embedded environment is broken in that the compiler is supposed to create a "function-pointer table" which is then used by the compiler to resolve calls to functions through a pointer. Unfortunately, the compiler is broken and doesn't generate a correct function-table.
So I don't have an easy way to extract the func address to invoke it.
--- Edit #2:
Ah, yes, the use of void *(set|get)_dispatcher was my attempt to see if the problem was with the typedefine of the func pointers. Originally, I had
typedef int (*set_fn_t)(cmdContext_t *pCmdCtx);
typedef int (*get_fn_t)(cmdContext_t *pCmdCtx);
typedef struct command {
const char *code;
set_fn_t set_dispatcher;
get_fn_t get_dispatcher;
const char *_description;
} command_t;
You should try changing your struct command so the function pointers have the actual type:
typedef struct command {
const char *code;
set_fn_t set_dispatcher;
get_fn_t get_dispatcher;
const char *_description;
} command_t;
Unfortunately, function pointers are not guaranteed to be able to convert to/from void pointers (that applies only to pointers to objects).
What's the embedded environment?
Given the information posted in the updates to the question, I see that it's really a bugged compiler.
I think that your proposed solution seems pretty reasonable - it's probably similar to what I would have come up with.
A function pointer isn't actually required to fit in a void*. You could check to make sure that the value you're calling is actually the address of the function. If not, use a function pointer type in the struct: either get_fn_t, or IIRC void(*)(void) is guaranteed to be compatible with any function pointer type.
Edit: OK, assuming that calling by value can't be made to work, I can't think of a neater way to do what you need than auto-generating the switch statement. You could maybe use an off-the-shelf ASP-style preprocessor mode for ruby/python/perl/php/whatever prior to the C preprocessor. Something like this:
switch(dispatcher_id) {
<% for c in commands %>
case SET_<% c.dispatcher %>: return set_<% c.dispatcher %>(pc);
case GET_<% c.dispatcher %>: return get_<% c.dispatcher %>(pc);
<% end %>
default:
return NOT_FOUND;
}
might be a bit more readable than the macro/include trick, but introducing a new tool and setting up the makefiles is probably not worth it for such a small amount of code. And the line numbers in the debug info won't relate to the file you think of as the source file unless you do extra work in your preprocessor to specify them.
Can you get the vendor to fix the compiler?
To what extent is the pointer-to-function broken?
If the compiler allows you to get the address of a function (I'm from C++, but &getenv is what I mean), you could wrap the calling convention stuff into assembler.
As said, I'm a C++ssie, but something in the way of
; function call
push [arg1]
push [arg2]
call [command+8] ; at the 4th location, the setter is stored
ret
If even that is broken, you could define an array of extern void* pointers which you define, again, in assembly.
try this syntax:
return (*((get_fn_t)commands[i].get_dispatcher))(pc);
It's been awhile since I've done C & function pointers, but I believe the original C syntax required the * when dereferencing function pointers but most compilers would let you get away without it.
Do you have access to the link map?
If so, maybe you can hack your way around the wonky function-pointer table:
unsigned long addr_get_dhcp = 0x1111111;
unsigned long addr_set_dhcp = 0x2222222; //make these unique numbers.
/* Relevant parts of header file */
typedef struct command {
const char *code;
unsigned long set_dispatcher;
unsigned long get_dispatcher;
const char *_description;
} command_t;
#define COMMAND_ENTRY(label,dispatcher,description) {(const char*)label,
addr_set_##dispatcher, addr_get_##dispatcher, (const char*)description}
Now compile, grab the relevant addresses from the link map, replace the constants, and recompile. Nothing should move, so the map ought to stay the same. (Making the original constants unique should prevent the compiler from collapsing identical values into one storage location. You may need a long long, depending on the architecture)
If the concept works, you could probably add a post-link step running a script to do the replacement automagically. Of course, this is just a theory, it may fail miserably.
Maybe, you need to look into the structure again:
typedef struct command {
const char *code;
void *set_dispatcher; //IMO, it does not look like a function pointer...
void *get_dispatcher; //more like a pointer to void
const char *_description;
} command_t;
Let say your dispatchers have the following similar function definition:
//a function pointer type definition
typedef int (*genericDispatcher)(int data);
Assume that the dispatchers are like below:
int set_DhcpDispatcher(int data) { return data; }
int get_DhcpDispatcher(int data) { return 2*data; }
So, the revised structure will be:
typedef struct command {
const char *code;
genericDispatcher set_dispatcher;
genericDispatcher get_dispatcher;
const char *_description;
} command_t;
Your macro will be:
#define COMMAND_ENTRY(label,dispatcher,description) \
{ (const char*)label, \
set_##dispatcher##Dispatcher, \
get_##dispatcher##Dispatcher, \
(const char*)description }
Then, you can set your array as usual:
int main(int argc, char **argv)
{
int value1 = 0, value2 = 0;
const command_t commands[] = {
COMMAND_ENTRY("DH", Dhcp, "DHCP (0=off, 1=on)")
};
value1 = commands[0].set_dispatcher(1);
value2 = commands[0].get_dispatcher(2);
printf("value1 = %d, value2 = %d", value1, value2);
return 0;
}
Correct me, if I am wrong somewhere... ;)

Resources