python "print" like function in c [closed] - c

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am new to C and I use to code in python, and I usually print too much variables and text to test my code and printf statement is irritating sometimes. I want to write a function in c which works exactly like print function in python.
I am facing two problem while writing the function.
I want to take n number of arguments as input to the function.
I want to take any data type as input to the function,
for Eg: print(12); print("hello"); print(123.12) should not raise error.
What have I done so Far
I found solution for taking n number of arguments using <stdarg.h>, but I have to specify the data type of the first argument which is not what I want.
"generic selection" Macros can be used to call different function on different data type of argument passed but not sure how it can be done, here is the link which I used for reference.

I want to write a function in c which works exactly like print function in python.
You simply cannot do that (because of type erasure : at runtime, type information is lost in C). Read Modern C then see this C reference.
In practice, you'll better write one function per datatype in C to print it. So it would be void print_int(int); to print an integer, void print_double(double); to print a double, etc. Once you have a collection of such functions you might use _Generic inside a macro (but that is rarely useful; it can handle a finite set of types).
Study for inspiration the source code of existing open source C software on github or elsewhere. Look for inspiration inside the source code of GNU bash, sqlite, GTK or GNU bison (and perhaps inside the source code of Python; half of the Python interpreter is coded in C)
Read also the documentation of your C compiler, e.g. GCC. So compile with all warnings and debug info: gcc -Wall -Wextra -g then use the GDB debugger.
Perhaps you want to implement some tagged union abstract data type in C. Then take inspiration from GNU guile or the runtime of Ocaml and dive inside their source code.
Once you are more familiar with C, read some C draft standard, e.g. n2176
Consider using Frama-C or the Clang static analyzer.
Consider also sometimes generating some C code, like SWIG does.
Budget weeks of work.

Related

How does code from different languages get integrated in the same platform? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
First and foremost, I'm no expert in software, and I realize this question might be as vague as it gets (it's just a curiosity), and get ready to read some barbaric guesses from my part!
The question came up from reading an article on how Linux's developers were implementing Rust into their OS (https://www.zdnet.com/article/linus-torvalds-on-where-rust-will-fit-into-linux/).
What does it even mean to implement Rust in their OS? Do they have some compiled code written in C that calls compiled code that resulted from writing in Rust? I don't see how this can efficiently be done, as you'd have different compilers probably being unable to optimize code, since, along the way, it's calling "foreign" code. I imagine the situation gets worse if you throw a language like Python or Java into the mix, which aren't precompiled. Now you would have JVM or PVM running together with compiled code, which, I imagine, would be highly impractical. One approach I can conceive, is if you see all these things as separate processes, and you'd simply have code from one language starting a process that corresponds to code from another language, but again, I imagine that wouldn't be very efficient...
Again, I realize I could've been more direct, but I'm not looking for a specific answer which addresses a problem, but rather general insight on how different languages can get used together. Thanks for understanding!
Typically when compiling a source file we have a set of options for outputs generated by the compiler, like creating a binary application from the main function, a statically linkable binary or a dynamically linkable library, or in other cases, source to source transformations.
The kernel is written in C, and to be able to compile large codebases like the kernel, we often decide to compile each, or a set of source files (the proper term would be translation unit https://en.wikipedia.org/wiki/Translation_unit_(programming)) into a statically linked library or object files. Once we've gathered all of the object files and statically (or shared) linked libraries we can link these together and produce a final binary/library.
When we're talking about integrating Rust code into the kernel, we're talking about using statically linked libraries from C in Rust and vice versa. The process of calling code produced from other compilers or languages is named Foreign Function Interface, or FFI.
There are many details and challenges with FFI including ABIs or name mangling to name a few. ABI, or application binary interface is one of the issues mentioned in your article. Unlike C, Rust does not have a stable ABI yet, meaning there's no guarantee the symbols in the static library compiled from Rust won't have different names or data layouts in the future. This means that code compiled using Rust's compiler may not be compatible with previous Rust compiler outputs which would require the C code to be updated every time there's an ABI change.
Here's how a C program is traditionally compiled:
Each source file is compiled - separately! - into an object file, which contains machine code, and placeholders for connecting all the object files together.
All the object files are joined together and the placeholders are filled in.
If you can generate some of those object files using Rust instead of C, the C compiler can't tell the difference. It's no different from a different C file!
You need to make sure the functions that cross the language barrier need to be valid functions for both languages. For example, you might not be able to pass structures as arguments, or return structures, if that's not valid in Rust (I don't actually know) - you might only be able to use primitive values, like ints and floats and pointers. If the Rust machine code expects float variables to be in certain registers, but the C machine code puts them in different registers, you might not be able to pass floats. Or you might have to put a special hint to one or the other compiler, to say "the argument goes in this register, dummy!" If the Rust compiler people didn't cooperate with the C compiler people, you are likely to run into a few of these kinds of problems, but with a bit of luck, they can all be worked around.
Since the function needs to be valid in both languages, you also need to write a C header file. You can't #include a Rust file - well you can, but it won't work - so you need to write the function declarations again in C syntax so the C compiler can understand what they are.
For languages which require VMs, it's complicated in a different way.
Usually these languages are so different from C that you can't just link together the machine code. Instead you have to use the VM's API to initialize the VM, load the code, and call the code. Something like this:
// not real code, just an illustration of how it could work
// How C starts a JVM and calls a Java method (a Java function)
void run_jvm() {
jvm_t *jvm = create_jvm();
jvm_class_t *main_class = jvm_load_class(jvm, "Main.class");
jvm_method_t *main_method = jvm_get_method(jvm, main_class, "main", NULL);
jvm_call(jvm, main_method, NULL, NULL);
delete_jvm(jvm);
}
// how Java calls a C function
void Java_HelloPrinter_printHello(jvm_t *jvm, jvm_object_t *this, jvm_args_t *args) {
printf("Hello world! My argument is %d\n", jvm_args_get_int(args, 1));
}
// how the method is declared in Java
public class HelloPrinter {
public static native void printHello(int i);
// ^^^^^^
// this means it's a C function
}
In Python or Lua, being more dynamic languages, the interpreter doesn't look for things for you. Instead, you put your functions into variables before you run any of your Python code.
// not real code, just an illustration of how it could work
// How Python calls a C function
void printHelloFunction(pvm_t *pvm, pvm_args_t *args) {
printf("Hello world! My argument is %d\n", pvm_args_get_int(args, 1));
}
// How C starts a PVM and calls a Python method
void run_python() {
pvm_t *pvm = create_pvm();
pvm_variable_t *var = pvm_create_global_variable(pvm, "printHello");
pvm_set_variable_as_c_function(pvm, var, &printHelloFunction);
pvm_load_module_from_file(pvm, "main.py");
delete_pvm(pvm);
}
These languages are not on equal footing with C, but Rust is, because Rust compiles to machine code. If you could run Java or Python code outside of a VM, they could be on equal footing. There used to be a compiler called gcj which would compile Java into machine code, but it's no longer maintained. Someone could write one, although it wouldn't run most Java programs, because a lot of those programs need to do stuff with the VM (like reflection).

Does C has any built in functions? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
There are around 50 built in functions in Python. The printf and scanf functions of C is comes under stdio.h library.
Are there any functions in C that are the part of language itself?
C has a few keywords, but no built-in functions. Every function you use comes from some other library. It is possible to compile a program even without the standard library using -nostdlib flag (for gcc).
It depends on what you mean by "part of the language". There are specifications that define what the C standard library should offer, so to that extent printf(), etc., are "part of the language".
However, a C compiler won't generate the code that implements these functions -- they are expected to be provided in a library of some kind. Most C compilers will know where/what the library is, and will be configured to link it automatically. You can almost certainly tell the compiler/linker not to do this, if you don't want to use the standard library. There are sometimes good reasons to.
Although there is a specification for a standard library, the language syntax itself has little-to-no coupling to the library. In Java, for example, if you add a String and an object, the compiler will generate code to call the object's toString() method. This method has to exist, because the Java language and the Java runtime library are closely related.
There's no real equivalent to this process in C -- C compilers can generate code in complete ignorance of what functions might be available. Those functions do need to be made available before runtime, but that's really the job of the linker, rather than the compiler.
However, gcc at least does have a notion of "built-in" functions. For example, if I try to compile this:
void printf (void)
{
}
I get a warning:
test.c:1:6: warning: conflicting types for built-in function
‘printf’; expected ‘int(const char *, ...)’ [-Wbuiltin-
declaration-mismatch]
even if I use the -nostdlib switch. Even with no standard library, gcc still thinks of printf() as being "built-in" even though it doesn't generate code for it.
I guess that notion of a "built-in function" isn't entirely clear-cut.
All C standard library functions are built into the language—they are part of the C language as defined by the C standard. C implementations (notably compilers) may implement these functions either as built-in functions implemented by the compiler or as object modules linked in by the linker. The C standard largely separates the rules that says how C programs must behave from rules about how C programs must be implemented.
In the sense of how a C program must behave, there is no difference between a built-in function or a linked-in function: The function behaves the same, and there is no way to describe an observable difference between the two implementations.
Compilers generally use a mix of built-in implementations and linked-in implementations. For example, in void foo(uint32_t u) { float f; memcpy(&f, &u, sizeof f); … }, a compiler may implement the memcpy by generating an instruction to move data from an integer register to a floating-point register and not by calling any external memcpy routine. For other memcpy calls, it might generate simple instructions to move bytes and again not call an external routine. For sqrt, it might generate a square-root instruction if the target machine has an appropriate one.
More complicated functions are more often implemented by calling external functions that are linked into the program after compilation. Even with many of these, the compiler may recognize special cases and provide calls to alternative functions (printf("Hello, world.\n") may be implemented as if it were puts("Hello, world."), instructions that perform the function without a call (pow(x, 2) may be implemented as a multiplication of x by itself), or results may be computed at compile time, by code built into the compiler (sin(.3) might be evaluated at at compile time).

display filename, line number and function in C without modifying the source code [duplicate]

This question already has answers here:
how to trace function call in C?
(10 answers)
Closed 8 years ago.
I am new in a company, working with C source code which almost lacks any kind of tracing mechanism.
I would like to know whether or not the application passes through a certain file and where (which function).
I could do this using breakpoints, but the concerned file contains a huge lot of functions.
Therefore I'm looking for some kind of tool, that I can attach to the application, and that gives an output of following kind:
-- Main.c (main_function())
---- submain.c (submain_function())
...
From that, I then could deduce where (which filename, which function) the application is passing.
Does anybody know whether or not such a tool exists?
Thanks
If you're on linux, gdb might come handy.
You can compile the code using -g or -g3 option with gcc, then run the binary using gdb ./<executable_name>, set a breakpoint on desired function in any of the source files and check the call.
While stepping through the application, it will show the filename and line number of the executing instruction.
Note: Please check this and this for a detailed understanding.
I assume you develop on Linux. Then you could also customize the GCC compiler, in particular using MELT (a lispy domain specific language to extend GCC), to have the compiler add some logging at many places. For that you'll need to insert a new GCC "optimization" pass doing such a job, and most importantly, you'll need to understand some details about GCC internal representations (Gimple, Tree-s, Basic blocks, ...)
However, that would probably require more than a week of work from your part. Unless your code base is really big (at least half a million
of lines) that might not worth the effort

About printf and scanf [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is the meaning that printf and scanf commands are the part of C language, as they don't need inclusion of #include<stdio.h>.
Why aren't others part of the C language?
What is the mean that,(print f) and (scan f) commands are the part of c language
They are not "commands", but rather functions, and they aren't part of the language either.
they don't need inclusion of #include
They do. They need the headers/declarations even more than others, since they are variadic. Not providing a prototype for them will quickly lead to undefined behavior.
why don't others be the part of c language
Again, these aren't part of the language because... because they are not part of the language. They are stand-alone functions, which don't contribute to the core syntax and semantics of a C program. They aren't included in C's context-free grammar. The C standard does describe them, though - since they are part of the C standard library.
Actually, no, they are not part of the language in the way you think they are. If you call print("hello, %d", 5); it will create an implicit declaration based on the parameters you've provided and the returning type will be int.
Luckily, there is a match for this in libc which is implicitly linked to your program, and linker will be able to link your source file and the library definition of printf.
In certain IDE, it is possible that printf & scanf are used and not underlined as false while editig the source code, because of the indexer which knows these functions exists. But you will not be able to compile it. The include is not optional as the compiler itselfs doesn't know printf nor scanf.
printf() and scanf() Example programs
In layman language
printf() is a function use to display (output)
scanf() is a function used for reading any input
printf and scanf aren't part of the grammar, but they are part of the language by virtue of being in the standard library as specified by the language definition. You do need to include stdio.h to use them properly, though.

matlab in C C++ and C C++ in matlab [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
It seems that are several ways to call matlab in C C++ and to call C C++ in matlab. While I try to list them here, please point it out If I miss something.
To call C C++ in matlab, there are also two methods. The first one is to call functions in C shared libraries. The second one is to build C C++ code into binary MEX-files, which will be called from the MATLAB command line. For the first method, are the C shared libraries are just general ones, i.e. without change to their C code for matlab and compiled from general C compiler like gcc?
To call matlab code in C C++, there are two methods available. The first one is Matlab engine. The second one is to use MATLAB Compiler mcc to create C or C++ shared libraries from your MATLAB code.
Besides matlab and C C++ can communicate via writing and reading data to and from some file (e.g. mat file, text file).
Having more than one ways to accomplish each of the goals here, could you tell me what cases are best for using which of them? i.e. calling functions in C shared libraries VS building C C++ code into binary MEX-files, Matlab engine VS compiling Matlab code into C C++ shared library.
Thanks and regards!
I only have expreience with calling C or C++ functions from MATLAB. It looks to me like the only difference between calling functions in a shared library and calling functions from a MEX file is that with a shared library, you have to call the function with 'calllib' which is a command line type function and MEX functions allow you to call functions as if they are built-in functions so the interface is a little cleaner.
My suggestion is to use MEX files if
You are using C++ (you may have to write a wrapper to use a C++ in a shared library)
You are using MATLAB as the glue for a large number of optimized C or C++ routines. You'll want to be able to call them cleanly.
Use shared library if
You already have an existing C library that can be used without modification.
You only need a small number of calls to C functions.
Really, it comes down to the interface. I personally prefer the MEX file route because it provides the cleanest interface from MATLAB to your C or C++ function. You can call it like just another function with standard MATLAB types. With a shared library, you may have to do some data formatting before calling the library function
I think the methods you've named are correct (it's been a while since I've used them)
The matlab C-compiler isn't really special; it is possible to use different compilers. See link list of supported compilers. This does not include gcc, but MS Visual studio is included. You'll run into issues when linking with the supplied libraries.
Basically: calling matlab from C is something you'd do if you need a tight interface; for instance if you want to synchronise 2 tools, or your S-function (simulink) requires additional information. But then, such a file is propably called by Matlab/simulink in the first place.
Calling c from matlab is what you want to do if you write your own S-functions or extensions to matlab.
The choice between C and C++ is yours; if you start from a blank sheet I suggest you use C++; you don't need to use the complete functionality but it allows more freedom. Also more libraries tend to be available for C++ nowadays.
C is the language of choice if you need to migrate to very different environments; i.e. to compile C to DSPs for instance. Or if you have got legacy code in C to start from. Mixing C and C++ is possible, but a can be a bit cumbersome; I'm sure you'll find topics on StackOverflow on this subject alone.

Resources