Is it possible to learn the functions using just header files? - function

In case of lack of proper updated tutorials for some particular library functions (in my case, latest allegro5), how can one learn by oneself how to call and use those functions? Is there some clue in header files?
thanks in advance

The header files are going to provide you with the bare minimum information required to correctly compile a program with those functions. It has the types, constants, and function prototypes. Nothing (short of comments) is going to explain how to correctly use the functions, just how to call them.
General
For example, if you see:
int do_something(int n, const char* desc);
You can only infer that you need to pass an integer n and a (C) string desc. That function returns an integer as well.
For a more complex example:
typedef struct {
int foo;
double bar;
} blam_t;
void munge(blam_t info);
You know that munge takes one argument of type blam_t which is a custom structure, as defined above. You could use that to create a blam_t variable and pass it to munge():
blam_t myvar;
myvar.foo = 42;
myvar.bar = 0.67;
munge(myar);
Allegro5
If we look at the source of include/allegro5/display.h we see things like this:
AL_FUNC(void, al_set_new_display_flags, (int flags));
This is an uncommon way of defining functions. They are using a macro AL_FUNC to define their functions. We see (by clicking on it) that AL_FUNC is defined as:
#define AL_FUNC(type, name, args) type name args
So that first example basically becomes:
void al_set_new_display_flags(int flags);
And we can call it with just an integer argument.
Without any documentation, you can only hope to learn by trying the functions. Then this becomes more a reverse engineering task.

Related

What are prototypes in programming?

This isn't a specific question about a language, but more about programming in general. The question came after I started an argument with a friend about "Function prototypes" which I learnt about recently from my C++ course. I mentioned to him that prototypes are function headers that you have to create at the beginning of your code so the compiler allocates some space at runtime before getting to the actual function. We then started rambling about whether other programming languages (Like java or python) which do not utilize function prototypes -- so far as we're concerned -- actually had a system similar to that of C++, just that they handled it themselves rather than having the user create them.
So we're curious to know, what are function prototypes after all? Are they only accountable on C/C++, or do other programming languages make use of them? And is it something I'd need to develop more on as a future programmer? Thanks for the help!
With respect to C and C++, the word "prototype" refers to a specific declaration syntax.
In the earliest versions of C, function definitions were written as
int func( arg1, arg2, arg3 ) // no types in argument list, just identifiers
int arg1;
double arg2;
char *arg3;
{
// function body
}
and declarations were written as
int func( ); // no argument list
The function argument list only contained identifiers and no type information - that was supplied separately. Function declarations didn't include arguments, just the return type.
C++ introduced and C later adopted the concept of prototype syntax, where the type information is included in the parameter list in both the definition:
int func( int arg1, double arg2, char *arg3 )
{
// function body
}
and the declaration
int func( int, double, char * );
This allowed compilers to check the number and types of arguments in a function call and issue diagnostics if they didn't match, rather than waiting until runtime to find out if there's a problem.
While the old-style function declaration and definition syntax is still supported, it should not be used for new code development - we're almost to the point where the word "prototype" is kind of redundant, since prototype syntax is the norm rather than the exception.
Statically-typed languages like Fortran and Pascal and Ada all have separate function declarations, but they don't refer to those declarations as prototypes. And again with C, "prototype" refers to a specific style of function declaration and definition, not just a declaration in and of itself.
This is greatly oversimplified, but the reason for function prototypes is "one-pass compilers."
If your compiler only makes one pass through the code, it needs to know what functions are available to it, before the function implementation is called. This is where prototypes come in.
Compilers that make multiple passes through the code build jump tables that tell it where all the functions are, so there's no need for function prototypes.
In C compilers, prototypes are used to check the type and number of function parameters (i.e. the function signature). This program:
#include <stdio.h>
int main()
{
printf("%d\n",add(3));
}
int add(int i, int j)
{
return i+j;
}
compiles and executes in Clang 7 with a warning, even though the result is meaningless (i.e. undefined behavior).
Whereas this program, incorporating a function prototype:
#include <stdio.h>
int add (int, int); /* function prototype for add */
void main()
{
printf("%d\n",add(3));
}
int add(int i, int j)
{
return i+j;
}
fails to compile.
C and C++ are compiled to native code and support calling between compilation units (files). To call a function XYZ from a neighboring compilation unit the compiler inserts a reference "calling XYZ" which is later resolved by the linker. But you need to know what to prepare on the stack for the function. The prototype supplies that information without having to compile the whole function.
Early C treated everything as int and as the C calling convention is caller-cleans-up, you as the caller know how many ints to remove from the stack after a function returns. If you call printf with three arguments without explaining what it is, the C compiler can still figure out what code to generate. If you misspelled it to vrintf it will compile but fail to link. So plain C worked (still works?) to some extent without prototypes (or treats missing prototypes as just a warning).
As C++ can pass all kinds of crazy stuff as function arguments, if you try to call something without explaining its argument types first, the compiler does not know what code to generate and you get an error.
This outside article is reasonably nice: http://www.cplusplus.com/articles/yAqpX9L8/

Why c++11 defines get<>(tuple) as a global function but not a member of tuple?

Seems std::get is just used on tuple class. Why not make it member class of tuple in standard library, any other usages?
The reason get is a non-member function is that if this functionality
had been provided as a member function, code where the type depended
on a template parameter would have required using the template
keyword.
source.
Snippet code when get is non-member function:
template<class T>
void foo ( tuple<T>& t ) {
get<0>(t) = 10; // get is non-member function
}
and another if get is member function of tuple:
template<class T>
void foo ( tuple<T>& t ) {
t. template get<0>() = 10; // ugly
}
Which version of get usage do you prefer ? For me, the first is better.
There is also a much older, less c++11 specific and generally more general version of an answer. (If you are only wondering about the specific case, you don't need to read on).
The general case for free functions is described in this classic DrDobb's article by an absolute C++ guru.
The short n sweet version: If you separate between public interface with access to private members and public interface with access to only the public interface you have a harder separation between a class and operations on that class.
It looks somewhat ugly, decreases helpfulness of most IDEs, but has some profound effects on your code modularity, especially when you embrace the template frenzy of the last std iterations. Matthias's answer depicts one clear example of this.
A more classic advantage is, that you can provide a set of free functions inside an extra header that a user can include on demand. Now think about interoperation between templated but otherwise completely separate classes A and B. You can now tie them together by providing a header like A_B_interop.h, full of free functions, without switching paradigms. You include that header, the classes become more powerful.

Why would one write a C++ lambda with a name so it can be called from somewhere?

Why would one write a C++ lambda with a name so it can be called from somewhere? Would that not defeat the very purpose of a lambda? Is it better to write a function instead there? If not, why? Would a function instead have any disadvantages?
One use of this is to have a function access the enclosing scope.
In C++, we don't have nested functions as we do in some other languages.
Having a named lambda solves this problem.
An example:
#include <iostream>
int main ()
{
int x;
auto fun = [&] (int y) {
return x + y;
};
std::cin >> x;
int t;
std::cin >> t;
std::cout << fun (fun (t));
return 0;
}
Here, the function fun is basically a nested function in main, able to access its local variables.
We can format it so that it resembles a regular function, and use it more than once.
A good reason to use names is to express intent. Then one can check that the lambda does 'the right thing' and the reader can check the intent. Given:
std::string key;
std::map<std::string, int> v;
one can write the following:
std::find_if( v.begin(), v.end(), [&](auto const& elem){ return elem.first == key; } );
but it's hard to tell whether it does 'the right thing'. Whereas if we spell it out:
auto matches_key = [&](auto const& elem){ return elem.first == key; };
std::find_if( v.begin(), v.end(), matches_key );
it is clearer that we do want the equality comparison and the readability is improved.
I see three things to consider when choosing between a named lamdba and a free function:
Do you need variables from the surrouding scope? If yes, choose a lamdba and leverage its closure. Otherwise, go with a free function (because of 3.).
Could the closure state equally well be passed as a function parameter? If yes, consider preferring a free function (because of 3.).
Do you want to write a test for the callable and/or reuse it in multiple translation units? If yes, choose a free function, because you must declare it in a header file and capturing variables in a lamdba closure
is a bit confusing in a header file (though this is debatable, of course).
requires the types to be known. You can't therefore live with forward declarations of function parameters and return types to reduce compilation times.
When your lambda is a recursive function by itself you have no choice but to give it a name. Also, an auto keyword won't suffice and you would HAVE to declare it using an std::function with the return type and the argument list.
Below is the example for a function that returns the Nth Fibonacci number:
std::function<int(int)> fibonacci = [&](int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
You have to give it a name in order to capture it with &. And auto won't work since lambda needs its to know its types before calling itself.
This is basicly an opinion based question. It's up to you, whether you prefer functions or lambdas, they are equivalent. A lambda shines, when you need variables from the surrounding. You just can capture them instead of passing it as a parameter, that's neat.
But beside of that, there is no difference.
when tuning a C++ application, a named lambda is easier to tune/trace, as compared to an anonymous/unamed lambda
I always consider lamdas as a nicety - I did plenty of C++ coding without them before they were introduced. So in some ways, I don't consider that there are many shoulds or shouldn'ts surrounding them. They are there to use however they make your life easier.
One time I use named lamdas is to scope a function - i.e. the lamda is only going to be used within another function - perhaps it does something a little dangerous, that you don't want other functions to have access to or perhaps you don't want to pollute the namespace.
If your lamda is too long to be an easy one-liner, but you don't want it to be
a available outside of your scope, then a named lamda is ideal way to produce tidy easy to read code.

Is vala a "pass by reference" or "pass by value"?

Or there exists pointers and references like C?
I'm trying to get started with vala but is good to know if vala is "pass by reference" or "pass by value"
First of all you should understand that the default vala compiler valac compiles to C (as an itermediate language). The code is then compiled using a C compiler (usually gcc).
valac -C example.vala will compile to example.c
So you can inspect the produced C code yourself.
Now to the real question:
Vala supports both call-by-value and call-by-reference. It is even a bit more fine grained than that.
Let's take an example using a plain C data type (int).
Call-by-value:
public void my_func (int value) {
// ...
}
The value will be copied into the function, no matter what you do with value inside my_func it won't affect the caller.
Call-by-reference using ref:
public void my_func (ref int value) {
// ...
}
The address will be copied into the function. Everything you do with value inside my_func will be reflected on the caller side as well.
Call-by-reference using out:
public void my_func (out int value) {
// ...
}
Basically the same as ref, but the value doesn't have to be initialized before calling my_func.
For GObject based data types (non-static classes) it gets more complicated, because you have to take memory management into account.
Since those are always managed using pointers (implictly) the ref and `out´ modifiers now reflect how the (implicit) pointer is passed.
It adds one more level of indirection so to speak.
string and array data types are also internally managed using pointers and automatic reference counting (ARC).
Though discouraged, Vala also does support pointers, so you can have an int * or MyClass * just like in C.
Technically, it pass by value since the underlying code is converted to C. Simple types (numeric types, booleans, enums, flags) are passed by value. Strings are passed by reference, but since they are immutable, they might as well be pass by value.
However, arrays, objects, and structs are all passed using pointers in C, so they are pass by reference. There is also the ref and out modifiers to function parameters that force those parameters to be passed by reference.

Function pointer to specific memory

I'd like to ask for an advice. I am working with small embedded uP.
I'd like to assign my various functions to myfunctions struct. How to do that correctly?
Then I want to place this myfunctions (struct of function pointers) to specific memory address (e.g. 0x1000). Whats is the best procedure to achieve this?
typedef void (*fptr)(void);
typedef struct FCN_IMAGE
{
fptr fcn1;
fptr fcn2;
fptr fcn3;
} FUNC_T;
FUNC_T myfunctions;
Actually it should be sort of jump table.
Secondly I want to read this function pointers from within other program - directly from specified address location (e.g. 0x1000).
It means the first code should assign the struct of function pointers to specific memory location and other independent code should read this table from specific memory. Interconnection between those two programs should be
#define FCN_BASE_ADDRESS (0x1000)
Any ideas what is the best way to achieve it?
P.S. This will run on embedded processor - not PC.
Locating objects at specific locations is usually most easily performed by the use of compiler specific extension; there is no standard method defined by the language. It may also be possible to locate a global object at a specific location by modifying the linker script, but that will be specific to your particular tool-chain
What compiler/tool-chain are you using? Refer to its documentation.
Maybe the following will help you:
// assign my various functions to myfunctions struct
myfunctions.fcn1 = &YourFunction1;
myfunctions.fcn2 = &YourFunction2;
myfunctions.fcn3 = &YourFunction3;
// assign the struct of function pointers to specific memory location
memcpy((void*)FCN_BASE_ADDRESS, &myfunctions, sizeof(myfunctions));
// read this table from specific memory
memcpy(&myfunctions, (void*)FCN_BASE_ADDRESS, sizeof(myfunctions));
This is based on my guess on what you actually want to do.
This is the best way to solve it in a portable manner:
typedef void (*fptr)(void);
#define FCN_BASE_ADDRESS ((volatile fptr*)0x1000)
/* Make myfunctions an array, not a struct.
Structs can have padding and aren't portable.
It doesn't look like you need a struct in this case.
*/
fptr myfunctions [N] =
{
fptr fcn1;
fptr fcn2;
fptr fcn3;
};
memcpy(&FCN_BASE_ADDRESS, myfunctions, sizeof(myfunctions));
Though if you are using Codewarrior, you could probably use a #pragma to allocate them where you want them. Here is an example assuming they are stored in read/write RAM and a 32-bit address bus.
// .prm file
SECTIONS
MEM_FCN_BASE_ADDRESS = READ_WRITE 0x2000 TO 0x200C;
END
PLACEMENT
FCN_BASE_ADDRESS INTO MEM_FCN_BASE_ADDRESS;
END
// .c file
#pragma DATA_SEG FCN_BASE_ADDRESS
fptr myfunctions[N] = ...;
#pragma DATA_SEG DEFAULT
If they should be stored in ROM/flash, for example a vector table, then it must be done differently with READ_ONLY sections, #pragma CONST_SEG and const fptr. (Note that the const keyword in C behaves in irrational ways when combined with typedef:ed pointers. In this case I believe it would give a constant pointer to a non-constant function and thus it should end up in NVM as desired.)