Hello (sorry for my bad english).
During my free time, I am doing a little application in python (3.5).
This application will have to call functions from a DLL made in C. I succeed to do it but I have a more "general" question. Let's take an example. I have four functions in my C code :
goNorth() {y++;}
goSouth() {y--;}
goWest() {x--;}
goEast() {x++;}
Easy to understand, just x and y coordinate, each function makes a move. My question is : Is there an easy way (and clean) to share the x and y betwwen all functions if I made a dll of this code ?
Julien
Yes, it is. Define the variable in an "implementation" file, and declare it as "extern" in a header file:
Implementation file:
// mylib.c
#include "mylib.h"
int x;
int y;
void goNorth() { ... }
void goSouth() { ... }
Headerfile:
// mylib.h
extern int x;
extern int y;
void goNorth();
void goSouth();
Related
I need to know what is meant by "Header" in C language? is it:
an area in the code, like header area in HTML code (a title> or declaration area? or definition area?, or kind of)?
or it is like a function (can be: function, or sub routine, or a scope, or kind of) that can be called.
A header is a convention generally accepted by C programmers.
It is a usually a .h file which is included into C source files which provides several benefits.
1.- Provides declaration of data types, global variables, constants and functions.
So you don't have to rewrite them time and again. And if they need being changed you just need to change it in a single file.
In example this program composed of two compliation units (two .c files) compiles and runs just fine.
// File funcs.c
#include <stdio.h>
struct Position {
int x;
int y;
};
void print( struct Position p ) {
printf("%d,%d\n", p.x, p.y );
}
// File main.c
struct Position {
int x;
int y;
};
int main(void) {
struct Position p;
p.x = 1; p.y = 2;
print(p);
}
But it is more mantainable to have the declaration for the struct Position in a header file and just #include it everywhere it is needed, like this :
// File funcs.h
#ifndef FUNCS_H
#define FUNCS_H
struct Position {
int x;
int y;
};
#endif // FUNCS_H
//File funcs.c
#include <stdio.h>
#include "funcs.h"
void print( struct Position p ) {
printf("%d,%d\n", p.x, p.y );
}
//File main.c
#include "funcs.h"
int main(void) {
struct Position p;
p.x = 1; p.y = 2;
print(p);
2.- Provides some type safety.
C features implicit declaration of functions. A "feature" (or rather an arguable language design mistake) which was fixed in C99.
Consider this program composed of two .c files :
//File funcs.c
#include<stdio.h>
int f(long n)
{
n = n+1;
printf("%ld\n", n );
}
// File main.c
int main(void)
{
f("a");
return 0;
}
With gcc this program compiles without warnings or errors. But does not behave as we could reasonable expect and desire :
jose#cpu ~/t/tt $ gcc -o test *.c
jose#cpu ~/t/tt $ ./test
4195930
Using a header file like this :
//File funcs.h
#ifndef FUNCS_H
#define FUNCS_H
int f(long n);
#endif // FUNCS_H
//File funcs.c
#include<stdio.h>
int f(long n) {
n = n+1;
printf("%ld\n", n );
}
// File main.c
#include"funcs.h"
int main(void) {
f("a");
return 0;
}
The program still compiles and works wrong but at least we get a warning :
jose#cpu ~/t $ gcc -o test *.c
main.c: In function 'main':
main.c:5:5: warning: passing argument 1 of 'f' makes integer from pointer without a cast
f("a");
^
In file included from main.c:2:0:
funcs.h:3:5: note: expected 'long int' but argument is of type 'char *'
int f(long n);
^
jose#cpu ~/t $ ./test
4195930
3.- Provide a public interface while letting the implementation details remain hidden.
When you design your program it is desirable to make it modular. That is to ensure that different parts of it (modules) are as independient as possible. So that when you need to make a change to one module you need not be worried about such change affecting other modules
Headers help in doing this because you put in the header of a modules the data structures, function prototypes and constants that will be needed by the users of such module.
The implementation details go into .c files.
That is how libraries work. The API interface is specified and distributed in header files. But the API code is in .c files which don't need to be distributed. As an user of the library you just need the headers and the compiled library, not its source code.
What is C header Linguistically?
Referring linguistically I'd say a C header file describes the interface as provided by a translation unit, namely the accompanying C file.
"interface" by means of
types
constants
(global) variables
functions
Not all of the above need to be part of a C header.
C headers are optional from the C language's perspective, but by convention they are expected to exist.
a header is a file with the .h extension.
It is meant to help the compiler to understand the symbol (method, function, struct, variable...) that are used within the code. See of it like an glossary at the end of a book.
It is used solely for development purpose.
It helps develloper knowing what function are available without having to look in all the implementation file. Like a man page.
A search on google? http://www.tutorialspoint.com/cprogramming/c_header_files.htm :)
Usually when talking about "headers" in C, what is meant is the files you include with the #include preprocessor directive. Those are called header files.
It could also be other things, like a comment at the top of a source (or header file) could be header. A comment before a function could be a function header.
Or when reading data files or data over the internet, many protocols have the data split into a header and the actual data (see e.g. HTTP).
I created a program in C that can find the determinant of a matrix
void fun1(); /*regardless of parameters they take*/
void fun2();
void fun3();
void fun4();
void fun5();
int global_var1; /*they are used among the above functions*/
int global_var2;
int global_var3;
int determinant;
int main(void){
int x,y;
for(x=0; x<something ; x++){
for (y=0 ; y<another_thing; y++){
fun1();
fun2();
fun3();
}
fun4();
fun5();
}
printf("Determinant is: %d\n", determinant);
return 0;
}
void fun1(){/*code goes here to process the matrix*/;}
void fun2(){/*code goes here to process the matrix*/;}
void fun3(){/*code goes here to process the matrix*/;}
void fun4(){/*code goes here to process the matrix*/;}
void fun5(){/*code goes here to process the matrix*/;}
Now I need to use this program to find the determinant of a given matrix in another project.
I created a header file, named it "matrix.h" and I replaced the int main(void) with int find_determinant() to be used in the new project.
the prototype of the second program:
#include "matrix.h"
int main(void){
find_determinant(); /*regardless of para it takes, it works perfectly*/
return 0;}
it works properly, nothing wrong with it, but the only problem that if I want to give this header file "matrix.h to someone to use it in his program, he can know the signature of other functions (useless for him alone and confusing) that were used to help in finding the determinant in int find_determinant().
My question is:
How can I hide (make them inaccessible) those functions and global variables and show only the int find_determinant() function in the second C file/program that contains #include "matrix.h" ?
Although you can put executable code in a header file, a good practice is to have your header file only contain declarations (for global variables) definitions and function prototypes. If you don't want to give your source code implementation, then you need to compile your functions into object code and provide the object file (either as a static archive or shared library) along with the header file. Whoever wants to use your function will then link his/her program to your objecet file/shared lib. This way, you can keep your source code implementation to yourself. Your header file would be:
#ifndef __SOME_MACRO_TO_PREVENT_MULTIPLE_INCLUSION__
#define __SOME_MACRO_TO_PREVENT_MULTIPLE_INCLUSION__
int find_determinant();
#endif
Beware of multiple inclusion problems (I have shown above how to avoid this so that if your matrix.h file is included several times, programs will still compile).
In one interview I was asked, if in one file A, some static function is defined and in file B you want to use this static function -- how you will use it?
My answers were:
declaring in .h file
But if we declare that in a header file, other files which will include this also have access to this static function.
wrapper concept: Declaring a new function newfun in file A, which will call static function and calling this newfun in file B.
But he was not satisfied with these answers.
Can you please provide me some better solution to violate static.
Perhaps they wanted to hear about function pointers?
You can create a pointer to the function, and call it using that pointer.
One possible scenario where this is reasonable is if you have a callback function that you don't want to be callable by everyone, and you give the pointer as an argument to some register_callback function.
Callback functions were used extensively, for example to let the user of a GUI API provide code for what should happen when a button is pressed. Nowadays, with object-oriented languages, it is more common to subclass a class and define or override methods, such as the Android View class and the method OnClickListener, but C# delegates are very similar to C function pointers.
To illustrate the principle, here is the source code (the file "B" in the original question) for some sort of library, where the main component is the do_stuff function:
#include <stdio.h>
#include "some_library.h"
void (*stored_callback)(void) = NULL;
void register_callback(void (*callback)(void)) {
stored_callback = callback;
}
void do_stuff(void) {
printf("Doing stuff...\n");
printf("Calling callback...\n");
if (stored_callback != NULL)
stored_callback();
}
This header, some_library.h, file shows the API of that library:
extern void register_callback(void (*callback)(void));
extern void do_stuff(void);
And here is how the library is used (the file "A" in the question):
#include <stdio.h>
#include "some_library.h"
static void my_callback(void) {
printf("Inside the callback!\n");
}
int main(void) {
register_callback(my_callback);
do_stuff();
return 0;
}
My interview answer would be "You can't."
(Because the question says "in file B you want to use this static function" and it didn't say you are allowed to modify file A.)
I'm assuming you don't have access to the source of the static function or else you could just remove the static keyword or expose the function via an exported wrapper or global function pointer.
You can still use the static function if you use objcopy to manually change the visibility on the symbol in the object file / library.
Suppose this is the (unaccessible) static function:
//static.c
#include <stdio.h>
static void fun(){
puts("Hello world");
}
Suppose you only have static.o, obtainable with gcc -c static.c.
Now, let's assume you want to link static.o with main.o made from
//main.c
void fun();
void main(){
fun();
};
To be able to link it, you need to turn
$ nm static.o
0000000000000000 t fun
U puts
into
0000000000000000 T fun
U puts
You can do that with:
objcopy --globalize-symbol=fun static.o global.o
Now you can link with global.o instead of static.o.
$ gcc main.o global.o && ./a.out
Hello world
filea.c
#include <stdio.h>
#include "filea.h"
static void hidden(void) { printf("inside hidden function.\n"); }
fxptr unhide(void) { return hidden; }
filea.h
#ifndef FILEA_INCLUDED
#define FILEA_INCLUDED
typedef void(*fxptr)(void);
fxptr unhide(void);
#endif
fileb.c
#include "filea.h"
int main(void) {
unhide()();
return 0;
}
I have a question about (re-)defining functions. My goal is to have a script where I can choose to define a function or not.
Like this:
void func(){}
int main(){
if (func)func();
}
AND without the function, just:
int main(){
if (func)func();
}
Anybody an idea?
You can do this in GCC using its weak function attribute extension:
void func() __attribute__((weak)); // weak declaration must always be present
int main() {
if (func) func();
// ...
}
// optional definition:
void func() { ... }
This works even if func() is defined in another .c file or a library.
Something like this, I think. Haven't used function pointers much, so I may have gotten the syntax slightly wrong.
void func()
{
#define FUNC_PRESENT
// code
}
void (*funcptr)();
#ifdef FUNC_PRESENT
funcptr = func;
#else
funcptr = NULL;
#endif
int main()
{
if (funcptr)
funcptr();
}
Use function pointers, set them dynamically based on runtime conditions, and check for null pointers or wrap them in methods that do that check for you.
Only option in C I can think of.
In C++ you could combine templates and DLLs to dynamically define at runtime.
Really the only way that you can "choose to define a function or not" is with C preprocessor directives. For example:
#ifdef some_name
void func() {
do_whatever();
}
#else
//the else part is optional
#endif
To set these "variables" you use #define some_name
The trouble is, all of this needs to be done at compile time (before that, actually) so it can't be done with an if statement like in your example. If you want an if statement to control your program flow, just use it and don't bother with trying to rename functions or using function pointers or something.
Introduction
I guess that you are trying to do this:
Two modules, a.o and b.o
b.o contains a definition for void foo()
a.o calls void foo() only if b.o is also linked into the final executable.
This could be useful for a "plugin" system.
Variation 1
You can simulate it using function pointers. I don't know enough C to write this in proper C code, but pseudocode looks like this:
a.h
extern collectionOfFuncPtrs_t list;
int addFuncPtr();
a.c
#include "a.h"
collectionOfFuncPtrs_t list;
int addFuncPtr(FuncPtr p) {
- add func ptr to list
- return 0
}
int main() {
- loop through list of function pointers
- call functions through them
}
b.c
#include "a.h"
void bar() { /* ... */ }
static int dummy = addFuncPtr(&bar);
c.c
#include "a.h"
void ayb() { /* ... */ }
static int dummy = addFuncPtr(&ayb);
Conclusion
Now, you can link in b.o and/or c.o as you wish, and int main() will only call bar() and/or ayb() if they exist.
Variation 2
Experiment with variations on this theme if it looks like it may be useful to you. In particular, if you have only a specific number of conditionally-defined functions, you could use a bunch of individual function pointers rather than some list:
a.h
extern fptr_t bar_ptr, ayb_ptr;
a.c
#include "a.h"
int main() {
if (bar_ptr)
bar_ptr();
if (ayb_ptr)
ayb_ptr();
}
b.c
#include "a.h"
void bar() { /* ... */ }
fptr_t bar_ptr = &bar;
b_dummy.c
#include "a.h"
fptr_t bar_ptr = 0;
c.c
#include "a.h"
void ayb() { /* ... */ }
fptr_t ayb_ptr = &ayb;
c_dummy.c
#include "a.h"
fptr_t ayb_ptr = 0;
Conclusion
Now either link b.o or b_dummy.o; and either link c.o or c_dummy.o.
I hope you get the general idea, anyway...!
Bootnote
This is a lot easier in C++ where you can write a module registration system very easily with std::maps and constructors.
In C? Only by using the preprocessor as stated in other answers.
C isn't a dynamic language like, say, Python.
The right way to do what I think you're asking about in C is to use function pointers. You can take the address of a function, assign it to a variable, test it for nil, etc. However, plain old C isn't a very dynamic language; you might be better off using a different language.
if you don't mind compiler specific extension, you can use __if_exists:
#include <iostream>
using namespace std;
// uncomment the following, and it'll still work
void maybeFunc(){ cout << "running maybe" << endl; }
int main(){
cout << "hi!" << endl;
__if_exists(maybeFunc)
cout << "maybe exists!" << endl;
maybeFunc();
}
}
this works in msvc by default, and in clang if you use the -fms-extensions flag.
Having namespaces seems like no-brainer for most languages. But as far as I can tell, ANSI C doesn't support it. Why not? Any plans to include it in a future standard?
For completeness there are several ways to achieve the "benefits" you might get from namespaces, in C.
One of my favorite methods is using a structure to house a bunch of method pointers which are the interface to your library/etc..
You then use an extern instance of this structure which you initialize inside your library pointing to all your functions. This allows you to keep your names simple in your library without stepping on the clients namespace (other than the extern variable at global scope, 1 variable vs possibly hundreds of methods..)
There is some additional maintenance involved but I feel that it is minimal.
Here is an example:
/* interface.h */
struct library {
const int some_value;
void (*method1)(void);
void (*method2)(int);
/* ... */
};
extern const struct library Library;
/* end interface.h */
/* interface.c */
#include "interface.h"
void method1(void)
{
...
}
void method2(int arg)
{
...
}
const struct library Library = {
.method1 = method1,
.method2 = method2,
.some_value = 36
};
/* end interface.c */
/* client code */
#include "interface.h"
int main(void)
{
Library.method1();
Library.method2(5);
printf("%d\n", Library.some_value);
return 0;
}
/* end client code */
The use of . syntax creates a strong association over the classic Library_function(), Library_some_value method. There are some limitations however, for one you can't use macros as functions.
C does have namespaces. One for structure tags, and one for other types. Consider the following definition:
struct foo
{
int a;
};
typedef struct bar
{
int a;
} foo;
The first one has tag foo, and the later is made into type foo with a typedef. Still no name-clashing happens. This is because structure tags and types (built-in types and typedef'ed types) live in separate namespaces.
What C doesn't allow is to create new namespace by will. C was standardized before this was deemed important in a language, and adding namespaces would also threaten backwards-compatibility, because it requires name mangling to work right. I think this can be attributed due to technicalities, not philosophy.
EDIT:
JeremyP fortunately corrected me and mentioned the namespaces I missed. There are namespaces for labels and for struct/union members as well.
C has namespaces. The syntax is namespace_name. You can even nest them as in general_specific_name. And if you want to be able to access names without writing out the namespace name every time, include the relevant preprocessor macros in a header file, e.g.
#define myfunction mylib_myfunction
This is a lot cleaner than name mangling and the other atrocities certain languages commit to deliver namespaces.
Historically, C compilers don't mangle names (they do on Windows, but the mangling for the cdecl calling convention consists of only adding an underscore prefix).
This makes it easy to use C libraries from other languages (including assembler) and is one of the reasons why you often see extern "C" wrappers for C++ APIs.
just historical reasons. nobody thought of having something like a namespace at that time. Also they were really trying to keep the language simple. They may have it in the future
Not an answer, but not a comment. C doesn't provide a way to define namespace explicitly. It has variable scope. For example:
int i=10;
struct ex {
int i;
}
void foo() {
int i=0;
}
void bar() {
int i=5;
foo();
printf("my i=%d\n", i);
}
void foobar() {
foo();
bar();
printf("my i=%d\n", i);
}
You can use qualified names for variables and functions:
mylib.h
void mylib_init();
void mylib_sayhello();
The only difference from namespaces it that you cannot be using and cannot import from mylib.
ANSI C was invented before namespaces were.
Because people who want to add this capability to C have not gotten together and organized to put some pressure on compiler author teams and on ISO bodies.
C doesn't support namespaces like C++. The implementation of C++ namespaces mangle the names. The approach outlined below allows you to get the benefit of namespaces in C++ while having names that are not mangled. I realize that the nature of the question is why doesn't C support namespaces (and a trivial answer would be that it doesn't because it wasn't implemented :)). I just thought that it might help someone to see how I've implemented the functionality of templates and namespaces.
I wrote up a tutorial on how to get the advantage of namespaces and/or templates using C.
Namespaces and templates in C
Namespaces and templates in C (using Linked Lists)
For the basic namespace, one can simply prefix the namespace name as a convention.
namespace MY_OBJECT {
struct HANDLE;
HANDLE *init();
void destroy(HANDLE * & h);
void do_something(HANDLE *h, ... );
}
can be written as
struct MY_OBJECT_HANDLE;
struct MY_OBJECT_HANDLE *my_object_init();
void my_object_destroy( MY_OBJECT_HANDLE * & h );
void my_object_do_something(MY_OBJECT_HANDLE *h, ... );
A second approach that I have needed that uses the concept of namespacing and templates is to use the macro concatenation and include. For example, I can create a
template<T> T multiply<T>( T x, T y ) { return x*y }
using template files as follows
multiply-template.h
_multiply_type_ _multiply_(multiply)( _multiply_type_ x, _multiply_type_ y);
multiply-template.c
_multiply_type_ _multiply_(multiply)( _multiply_type_ x, _multiply_type_ y) {
return x*y;
}
We can now define int_multiply as follows. In this example, I'll create a int_multiply.h/.c file.
int_multiply.h
#ifndef _INT_MULTIPLY_H
#define _INT_MULTIPLY_H
#ifdef _multiply_
#undef _multiply_
#endif
#define _multiply_(NAME) int ## _ ## NAME
#ifdef _multiply_type_
#undef _multiply_type_
#endif
#define _multiply_type_ int
#include "multiply-template.h"
#endif
int_multiply.c
#include "int_multiply.h"
#include "multiply-template.c"
At the end of all of this, you will have a function and header file for.
int int_multiply( int x, int y ) { return x * y }
I created a much more detailed tutorial on the links provided which show how it works with linked lists. Hopefully this helps someone!
You can. Like other's answer, define function pointers in a struct.
However, declare it in your header file, mark it static const and initialize it with the corresponding functions.
With -O1 or higher it will be optimized as normal function calls
eg:
void myfunc(void);
static const struct {
void(*myfunc)(void);
} mylib = {
.myfunc = myfunc
};
Take advantage of the #include statement so you do not need to define all functions in one single header.
Do not add header guards as you are including it more than once.
eg:
header1.h
#ifdef LIB_FUNC_DECL
void func1(void);
#elif defined(LIB_STRUCT_DECL)
struct {
void(*func)(void);
} submodule1;
#else
.submodule1.func = func1,
#endif
mylib.h
#define LIB_FUNC_DECL
#include "header1.h"
#undef LIB_FUNC_DECL
#define LIB_STRUCT_DECL
static const struct {
#include "header1.h"
#undef LIB_STRUCT_DECL
} mylib = {
#include "header1.h"
};