How can I Pass variables to C program using gcc ??
For example
gcc -o server ./server.c --host=localhost --port=1234
how to access these variables in my code ?
Thank you.
Your question isn't clear; there are at least two things you might be asking about: how to access command line arguments passed to your program when it is run and how to access arguments passed to the compiler when your program is compiled.
Command line arguments:
./server --host=localhost --port=1234
These are accessed via arguments to main():
int main(int argc, char *argv[]) {
for (int i=0; i<argc; ++i) {
std::cout << argv[i] << '\n';
}
}
getopt is a pretty common way to parse these command line options, though it isn't part of the C or C++ standards.
Compiler arguments:
You can't necessarily access arguments passed to the compiler, but for the arguments you can detect you detect them through changes to the compile environment. For example if the compiler takes an option to enable a language feature then you can detect when that option is passed by detecting if the feature is enabled.
gcc -std=c11 main.cpp
int main() {
#if 201112L <= __STDC_VERSION__
printf("compiler was set to C11 mode (or greater).\n");
#else
printf("compiler set to pre-C11 mode.\n");
#endif
}
Additionally you can directly define macros in command line arguments to the compiler that the program will be able to access.
gcc -DHELLO="WORLD" main.cpp
int main() {
#if defined(HELLO)
printf("%s\n", HELLO);
#else
printf("'HELLO' is not defined\n");
#endif
}
If you want to define them at compile-time see the -D param, if you want to define them at runtime use something like
int main(int,char**);
int main(int argsc/*argument count*/, char**argv/*argument vector*/)
{
int i;
for(i=0;i<argsc;i++)
{
printf("%s\n",argsv[i]);
}
return 0;
}
If you want to pass variables to your program execution, you can use environment variables. Like this:
char* myOption = getenv("MY_OPTION_NAME");
if(!myOption) myOption = "my default value";
//Do whatever you like with the value...
And when you call your program, you can set the variables inline by assigning them before the program name:
MY_OPTION_NAME="foo" ./server
You could also set your environment variables once and for all using
export MY_OPTION_NAME="foo"
Related
The code is like (real noob question) :
int main(int argc, char **argv){
//some code
}
I know, it means I have to give some arguments while executing in the terminal, but the code does not require any arguments or information from the user. I don't know what to give as the argument?
For example:
#include <stdio.h>
int main(int argc, char **argv)
{
printf("Hello World\n");
}
Compile with GCC,
$gcc prog.c -o prog
$./prog
Hello World
So, If you do not use agave in your code, then, there is no need to provide an argument.
I have to give some arguments while executing in the terminal,
No, you don't have to. You may give some arguments. There are conventions regarding program arguments (but these are just conventions, not requirements).
It is perfectly possible to write some C code with a main without argument, or with ignored arguments. Then you'll compile your program into some executable myprog and you just type ./myprog (or even just myprog if your PATH variable mentions at the right place the directory containing your myprog) in your terminal.
The C11 standard n1570 specifies in §5.1.2.2.1 [Program startup] that
The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters:
int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent) or in some other implementation-defined manner.
The POSIX standard specifies further the relation between the command line, the execve function, and the main of your program. See also this.
In practice I strongly recommend, in any serious program running on a POSIX system, to give two argc & argv arguments to main and to parse them following established conventions (In particular, I hate serious programs not understanding --help and --version).
You can always pass some number of arguments or pass nothing unless you are checking for the number of arguments and arguments passed (or forcing compiler to do so). Your command interpreter has no idea what your program is going to do with the passed argument or whether the program need any argument. It's your program which takes care of all these things.
For example,
int main(void){
return 0;
}
you can pass any number of arguments to the above program
$ gcc hello.c -o hello
$ ./hello blah blah blah
In case of
int main(int argc, char **argv){
return 0;
}
you can pass no arguments.
$ gcc hello.c -o hello
$ ./hello
For
int main(int argc, char **argv){
if(argc < 3){
printf("You need to pass two arguments to print those on the terminal\n");
exit(0);
}
else{
printf("%s %s\n", argv[1], arv[2]);
}
return 0;
}
You have to pass two arguments because the program checking the number of arguments passed and using them
$ gcc hello.c -o hello
$ ./hello Hello world
Is it possible to write a script to run this code for different values of A;
#include <stdio.h>
#define A 3
int main (){
printf("In this version A = %d\n", A);
return(0);
}
I guess something like for loop?
Is it possible to write a script to run this code for different values of A;
Not as it is because the macro A has a fixed value defined in your code. Instead you can pass the value as an argument:
#include <stdio.h>
int main(int argc, char **argv){
if(argc == 2) {
printf("In this version A = %s\n", argv[1]);
}
return 0;
}
(The code doesn't check if its input is an integer -- which you can test if necessary).
and you can run it via script. For example, compile the above (gcc -Wall -Wextra test.c -o test) using a for loop of bash:
$ for ((i = 0; i < 10; i++)); do ./test $i; done
In this version A = 0
In this version A = 1
In this version A = 2
In this version A = 3
In this version A = 4
In this version A = 5
In this version A = 6
In this version A = 7
In this version A = 8
In this version A = 9
$
No. But you can make A a command line arg:
#include <stdio.h>
int main (int argc, char *argv[]) {
int a;
if (argc != 2 || sscanf(argv[1], "%d", &a) != 1) return 1;
printf("In this version A = %d\n", a);
return 0;
}
Compile to a binary named foo, then
foo 42
will print
In this version A = 42
You can also compile different versions by defining A in the compilation command line. From your original program, remove the #define. Then
gcc -DA=42 foo.c -o foo
./foo
will print the same as above.
DO you need run program repeated from script? why not to make program that accepts arguments from command line?
1)The main() function actually takes arguments, you can compile program once and pass different parameters, as shown in answers above
2) If you need to change some code parameters from make script, I'd say, create separate header that would contain defines and write script that would echo into that file (> for start, >> to continue writing).
3) Alternative way you can call you compiler with flag that would be equal to #define macro-command. For gcc it's -D, for example -DA=3 instead of #define A 3.
Most programs use makefile to be compiled. For that case you can script make file to use 2) or 3) Former is preferable because you do not need to pass that argument to all compilation targets, reducing time or re-compiling. There are tools for more advanced manipulations, like autoconf.
Under Linux, I can register a routine that will run before main. For example:
#include <stdio.h>
void myinit(int argc, char **argv, char **envp) {
printf("%s: %s\n", __FILE__, __FUNCTION__);
}
__attribute__((section(".init_array"))) typeof(myinit) *__init = myinit;
By compiling this with GCC and linking it in, the function myinit will be run before main.
Is there way to do this under Mac OSX and MACH-O?
Thanks.
You could place the function in __mod_init_func data section of Mach-O binary.
From Mach-O format reference:
__DATA,__mod_init_func
Module initialization functions. The C++ compiler places static constructors here.
example.c
#include <stdio.h>
void myinit(int argc, char **argv, char **envp) {
printf("%s: %s\n", __FILE__, __FUNCTION__);
}
__attribute__((section("__DATA,__mod_init_func"))) typeof(myinit) *__init = myinit;
int main() {
printf("%s: %s\n", __FILE__, __FUNCTION__);
return 0;
}
I build your example with clang on OS X platform:
$ clang -Wall example.c
$ ./a.out
example.c: myinit
example.c: main
Easiest way is to specify the function to be constructor using constructor attribute. The constructor attribute causes the function to be called automatically before execution enters main(). Similarly, the destructor attribute causes the function to be called automatically after main() completes or exit() is called. You can also specify optional priority if you have several functions
e.g. __attribute__((constructor(100)))
#include <stdio.h>
__attribute__((constructor)) void myinit() {
printf("my init\n");
}
int main() {
printf("my main\n");
return 0;
}
__attribute__((destructor)) void mydeinit() {
printf("my deinit\n");
}
$ clang -Wall example.c
$ ./a.out
my init
my main
my deinit
Disclaimer: I generally discourage what I'm about to say. Having code running before or after main makes things less predictable. I'm not sure why you wouldn't just let the first line of main invoke your myinit, but I suppose everyone has a reason. Here goes.
I don't know much about Mach-O, but the simplest way to run code before main, is to link in a C++ class that has a corresponding global instance defined. You can do this independently of your "C" code without having to alter anything else. You can also have this C++ code invoke C functions defined elsewhere in your code. In the example below, I show a simple example of how I would invoke your myinit.
In a standalone .cpp (or .cc) file, declare a very simple C++ class with a constructor that calls your "myinit function".
foo.cpp
// forward declare your myinit function and designate "C" linkage
extern "C" myinit(int, char**, char**);
class CodeToRunBeforeMain
{
public:
CodeToRunBeforeMain()
{
// invoke your myinit function here
myinit(0, NULL, NULL);
}
};
// global instance - constructor will run before main.
CodeToRunBeforeMain g_runBeforeMain;
The above approach doesn't recognize argc, argv, or envp. Hopefully, that isn't important.
I have a homework assignment that requires us to open, read and write to file using system calls rather than standard libraries. To debug it, I want to use std libraries when test-compiling the project. I did this:
#ifdef HOME
//Home debug prinf function
#include <stdio.h>
#else
//Dummy prinf function
int printf(const char* ff, ...) {
return 0;
}
#endif
And I compile it like this: gcc -DHOME -m32 -static -O2 -o main.exe main.c
Problem is that I with -nostdlib argument, the standard entry point is void _start but without the argument, the entry point is int main(const char** args). You'd probably do this:
//Normal entry point
int main(const char** args) {
_start();
}
//-nostdlib entry point
void _start() {
//actual code
}
In that case, this is what you get when you compile without -nostdlib:
/tmp/ccZmQ4cB.o: In function `_start':
main.c:(.text+0x20): multiple definition of `_start'
/usr/lib/gcc/i486-linux-gnu/4.7/../../../i386-linux-gnu/crt1.o:(.text+0x0): first defined here
Therefore I need to detect whether stdlib is included and do not define _start in that case.
The low-level entry point is always _start for your system. With -nostdlib, its definition is omitted from linking so you have to provide one. Without -nostdlib, you must not attempt to define it; even if this didn't get a link error from duplicate definition, it would horribly break the startup of the standard library runtime.
Instead, try doing it the other way around:
int main() {
/* your code here */
}
#ifdef NOSTDLIB_BUILD /* you need to define this with -D */
void _start() {
main();
}
#endif
You could optionally add fake arguments to main. It's impossible to get the real ones from a _start written in C though. You'd need to write _start in asm for that.
Note that -nostdlib is a linker option, not compile-time, so there's no way to automatically determine at compile-time that that -nostdlib is going to be used. Instead just make your own macro and pass it on the command line as -DNOSTDLIB_BUILD or similar.
I am trying to do this (is this possible?) with GCC compiler:
Specifiy a function but this function if is not implemented point to a NULL. Example:
extern void something(uint some);
And if this is unimplemented point to a NULL value.
So it's possible check like this:
something != NULL ? something(222) : etc.;
I would like solution with trough GCC (this could be solvable with function pointers).
This is definitely not portable, but gcc can do this with weak symbols on some platforms. I know this works on Linux and *BSD, but doesn't work on MacOS.
$ cat weak.c
#include <stdio.h>
extern int foo(void) __attribute__((__weak__));
int
main(int argc, char **argv)
{
int x = foo ? foo() : 42;
printf("%d\n", x);
return 0;
}
$ cat weak2.c
int
foo(void)
{
return 17;
}
$ cc -o weak weak.c && ./weak
42
$ cc -o weak weak.c weak2.c && ./weak
17
$
You can do this using GCC's weakref attribute:
extern void something(int);
static void something_else(int) __attribute__((weakref("something")));
int main()
{
if (something_else)
something_else(122);
}
If something is not defined in the program then the weak alias something_else will have an address of zero. If something is defined, something_else will be an alias for it.
Essentially you are trying to get the compiler to locate a function at the memory address 0 (NULL). This cannot be done in C without platform/compiler specific constructs.
One question though, is why you would ever want to do this. C is a static language, so if you know that the function will never exist during compilation you might as well just use the pre-processor to tell the rest of the program about this at compile time. Indeed these sorts of compile time substitutions are precisely why the preprocessor is there in the first place.
I would create a macro that you define if your function exists as follows:
#define THE_SOMETHING_FUNCTION_EXISTS
Then replace anywhere you would have tested for something == NULL with an #ifdef instead.
Of course, if the function’s existence might change at run-time then the correct way to implement the behaviour you want is to make something a function pointer.