What is the best way to accomplish the following in C?
#include <stdio.h>
struct A
{
int x;
};
struct A createA(int x)
{
struct A a;
a.x = x;
return a;
}
struct A a = createA(42);
int main(int argc, char** argv)
{
printf("%d\n", a.x);
return 0;
}
When I try to compile the above code, the compiler reports the following error:
"initializer element is not constant"
The bad line is this one:
struct A a = createA(42);
Can someone explain what is wrong? I'm not very experienced in C. Thanks!
struct A a = { .x = 42 };
More members:
struct Y {
int r;
int s;
int t;
};
struct Y y = { .r = 1, .s = 2, .t = 3 };
You could also do
struct Y y = { 1, 2, 3 };
The same thing works for unions, and you don't have to include all of the members or even put them in the correct order.
Why not use static initialization?
struct A a = { 42 };
The problem here is that global / file static variables in C must have a value known at compile time. This means you can't use a user defined function to initialize the value. It must be a constant expression
For curious people who also use MSVC:
In C it is possible to run initialization functions before main just as it is possible in C++ (of course it is, how would C++ do it if it wasn't possible in C), however it may be somewhat confusing if you haven't read how does your runtime library work.
Long story short:
#pragma section(".CRT$XIU",long,read)
int
init_func ()
{
// initialization
return 0; // return 0 is mandatory
}
__declspec(allocate(".CRT$XIU"))
int (*global_initializer)() = init_func;
So it's not as compact source text as in C++, but it can be done. Also, before using I recommend to understand PE format first, then read crt\src\crt0.c and crt\src\crt0dat.c (search for _cinit in both files) in your MSVC installation directory so you know what is going on.
You cannot invoke functions in static initialization like that. In your example, you can simply use:
struct A a = {42};
If you have a more complicated setup, you will need to provide a library construction and library destruction function that you force users of your library to call (assuming you want to be portable), or you will have to use C++ and take advantage of constructors/destructors, or you will have to take advantage of the non-standard and non-portable __attribute__((constructor)) to create a function that is run on startup to initialize it.
If you have more complicated setup, I would strongly advocate that you use C++:
class A
{
A(){
// can do initialization in the constructor
}
// ...
};
A a;
However, if you need to stick with pure C, the portable thing to do is use something like:
typedef void* mylibrary_attr_t;
typedef void* mylibrary_t;
#ifdef __cplusplus
# define EXTERNC extern "C"
#else
# define EXTERNC
#endif
EXTERNC int mylibrary_attr_init(mylibrary_attr_t*);
EXTERNC int mylibrary_attr_setparam1(mylibrary_attr_t,int);
EXTERNC int mylibrary_attr_setparam2(mylibrary_attr_t,double);
// .. more functions for various attributes used by library
EXTERNC void mylibrary_attr_destroy(mylibrary_attr_t*);
EXTERNC int mylibrary_init(mylibrary_t*,mylibrary_attr_t);
EXTERNC void mylibrary_destroy(mylibrary_t*);
// functions that use mylibrary_t
// ...
Basically, in the above, you would initialize your library with mylibrary_init and teardown your library using mylibrary_destroy. The functions using your library would require an initialized instance of mylibrary_t, and so the person who created the main function would be responsible for invoking mylibrary_init. It is also good to make the initialization function dependent on an "attributes" parameter that can be replaced with 0 or NULL as a default. That way, if you extend your library and need to accept configuration options, it is available to you. That's more a design than technical approach, though.
Related
I have learned a decent amount of java and now I want to learn C, I've learned a little about structs and typedefs but I have errors when I place the typedef after the main() function and it is used from within the main() function.
Is there a way to declare types but not define them in C so I can keep my code after the main() function similar to functions? (I'm not sure if this is good practice but I like organizing my code this way)
Don't do that. C code is intended to be read by the compiler and it will learn about new definitions as it keeps reading the file. Moving things below main() serves no purpose. It will also confuse other humans.
As for the question itself: in some cases, yes, you can. If everything you need is a forward declaration, you can do so. But in most cases you will want the definition, so it won't help you.
For example, this will compile:
struct T;
int main(void)
{
struct T * p = 0;
return !!p;
}
// Later on you may define `struct T`
C requires a type to be declared before it's used. If the code is just using a pointer to the type then the code doesn't not need to declare the members, this is a forward declaration. Other usage, such as passing the type by value or using it as a local variable requires a full definition.
C projects generally use headers which will provide the definition of types. These are included into the C modules.
// header.h
#ifndef _header_h_
#define _header_h_
struct DescribedType {
int member;
char* variables;
};
#endif
// module.c
#include "header.h"
struct ForwardDeclaration;
ForwardDeclaration* allocForward();
int main(){
DescribedType someType;
ForwardDeclaration* someValue = allocForward();
return 0;
}
struct ForwardDeclaration {
int declaredLater;
};
I have the following c code:
struct {
short s;
int n;
} variableName;
I want to write a function to capture this variable like so
void func(MyStruct* var){
//do stuff
}
func(&variableName);
I would like to do this without providing a definition for the struct. Is there a way to capture variableName?
No, you can't pass an "anonymous" struct into a function in C. You could of course define your function to accept the arguments individually:
void func(short s, int n) { ... }
Or you can define the MyStruct structure in a place that both the function and the calling code has visibility to. Note that the whole struct is passed by value (copy) when you do that, which may be the behavior you want here (or may not be).
You may be looking for something more like a "dictionary" or "associative array" or "hash" type that many other languages provide, with arbitrary key value pairs in it. Pure C does not have a facility for this; the compiler wants to know the layout of a structure in advance.
(I'm not sure if you might be asking about a slightly more esoteric idea, which is hiding the composition of a structure and passing around an "opaque handle" out of and into an API. There are ways to structure that in C, but please say so if that's what you're talking about.)
Completely overlooked "I would like to do this without providing a definition for the struct. Is there a way to capture variableName?" in the OP, unless it was edited after. The question makes less sense now, but heres how you could normally pass a struct to a function for future readers.
#include <stdio.h>
struct StructName{
short s;
int n;
};
void func(struct StructName struct_var){
printf("Param values are: %4X %4X\n", struct_var.s & 0xFFFF, struct_var.n & 0xFFFF);
}
int main(){
struct StructName struct_var;
struct_var.s = 0xDEAD;
struct_var.n = 0xBEEF;
func(struct_var);
}
//It looks like you are trying to use the definition as a variable. Here the definition is StructName and the variable is struct_var.
this sample code outputs:
Param values are: DEAD BEEF
If you use clang or gcc, you may be able to use typeof:
struct foo {
struct {
int i;
} anon;
} foo;
void do_something(typeof(foo.anon)* member) {
member->i = 1;
}
If there is no global instance of your type, you may be able to use typeof((struct foo){}.anon).
This comes with a lot of downsides. The most obvious ones are that:
it's not standard, and it ties you to clang/gcc
it's pretty darn ugly
it might not behave as you expect anyway
For instance, structurally-equivalent anonymous types do not have the same type, so in something like this:
struct foo {
struct {
int i;
} anon1;
struct {
int i;
} anon2;
} foo;
anon1 and anon2 both have a different type, meaning that typeof one of them cannot be used to refer to both.
In the long run, you will almost certainly find that it's worth naming the structures, especially if you use them as function arguments. For instance, if you want to make your variable available from a header, I think that you'll have to work pretty hard to keep it anonymous.
Although it's not particularly pretty and not compatible with C++, C puts the name of nested declarations in the global namespace, so this is portable and it's not a very big code change to front-load:
struct {
struct not_anon {
int i;
} anon;
} foo;
void do_something(struct not_anon* member) {
member->i = 1;
}
There are a lot of questions out there about forward declarations and opaque types, but most seem to be from the perspective of the library author, or people trying to use incomplete types without pointers or some such.
I'm using a library whose interface accepts/returns FOO * pointers. I'd like to confirm that I cannot (or should not) somehow forward-declare FOO or FOO * in my header file (which defines a struct with a FOO * member).
I do know that I could just #include <library.h> in both my header and my .c file, but since this is really just a learning project, I wanted to get clarification. (On the one hand, it seems like a forward-declaration might be possible, since my struct member is only a pointer and thus its size is known without knowing what FOO is—but on the other hand, I don't know if it's valid/smart to typedef something to FOO when the library is already doing that.)
Thanks in advance!
Assuming you never need to dereference the pointer, then you can use an opaque type pointer if you know the struct tag name for it:
typedef struct FOO FOO;
You can now create FOO * variables, and use them. And you probably could find the structure tag from the header file, but you should be aware that the library owners could change it at any time.
It is still usually best to include the official header, but if most of your code is not accessing the actual library, just passing around a handle to something returned by the library, you can avoid the 'cost' of including the actual header. You should measure what that cost is before deciding on what is probably premature optimization. It might be argued that if you have to ask the question, you don't know enough to be sure of doing it right, and you're in danger of getting burnt.
Note that you cannot create actual variables of the type; for that to work, the compiler needs to know how big the structure actually is, which means you need the details from the header.
Strictly speaking, if you don't know the tag name, that won't work. And likewise, if the structure doesn't have a tag, you can't do it either. And if it isn't a structure type, you can't do it.
Note that if you know the structure tag, you can also write:
struct FOO *fp;
If you have to get inventive, everything works for passing around pointers until you reach the point where you need to access the actual library functions. Then you need the actual library header (to make sure the information is right), and if your structure tag is wrong, all hell breaks loose. So, if you're going to play this game, make sure you get the structure tag correct.
Note that C11 allows a typedef to be repeated as long as it is the same each time, whereas earlier versions of C did not allow that. This can be a considerable help.
Working example
This is close to a minimal example that shows how it might be done. It assumes C11 where the repeated typedef is legitimate. It won't work for C99 or C89/C90 because the typedef for FOO is repeated when projfunc.c is compiled. (There are various ways you can adapt it so that it will work in C99 or earlier, but they're messier, using #ifdef or similar around the project.h typedef — since the presumption is that you can't alter library.h; if you can, it is part of your project after all.)
The project.h header is used primarily by the general code that belongs to the project that uses the library defining FOO — which is represented by projmain.c in this example. It can be used on its own, or with library.h, which is illustrated by projfunc.c which is the project code that actually interfaces to the library and makes calls to the library. The file library.c only uses library.h.
You can play with alternative declarations of FOO in project.h to see what goes wrong where. For example, typedef struct BAR FOO; will fail; so will typedef struct FOO *FOO;.
project.h
#ifndef PROJECT_H_INCLUDED
#define PROJECT_H_INCLUDED
typedef struct FOO FOO;
typedef struct Project
{
FOO *foop;
char *name;
int max;
double ratio;
} Project;
extern int proj_function(Project *pj);
#endif /* PROJECT_H_INCLUDED */
library.h
#ifndef LIBRARY_H_INCLUDED
#define LIBRARY_H_INCLUDED
typedef struct FOO
{
int x;
int y;
} FOO;
extern FOO *foo_open(const char *file);
extern int foo_close(FOO *foop);
extern int foo_read(FOO *foop, int *x, int *y);
extern int foo_write(FOO *foop, int x, int y);
#endif /* LIBRARY_H_INCLUDED */
projmain.c
#include "project.h"
int main(void)
{
Project pj = { 0, 0, 0, 0.0 };
if (proj_function(&pj) != 0)
return 1;
return 0;
}
projfunc.c
#include "project.h"
#include "library.h"
#include <stdio.h>
int proj_function(Project *pj)
{
int x, y;
pj->foop = foo_open("classic-mode");
if (foo_write(pj->foop, 1, 2) < 0)
{
foo_close(pj->foop);
return -1;
}
if (foo_read(pj->foop, &x, &y) < 0)
{
foo_close(pj->foop);
return -1;
}
printf("x = %d, y = %d\n", x, y);
return 0;
}
library.c
#include "library.h"
#include <assert.h>
static FOO foo = { 0, 0 };
FOO *foo_open(const char *file)
{
assert(file != 0);
return &foo;
}
int foo_close(FOO *foop)
{
assert(foop == &foo);
foo.x = foo.y = 0;
return 0;
}
int foo_read(FOO *foop, int *x, int *y)
{
assert(foop == &foo);
*x = foop->x + 1;
*y = foo.y + 1;
return 0;
}
int foo_write(FOO *foop, int x, int y)
{
assert(foop == &foo);
foo.x = x + 1;
foop->y = y + 2;
return 0;
}
The library should define FOO for you, either opaquely or transparently, as it's own source refers to FOO.
#include <library.h> should get you the prototypes to the functions the library provides, and also the types needed to interact with them.
If you create your own FOO type, you'll almost certainly get a compile error indicating multiple definition of 'FOO' when you include the function prototypes from the library.
Having the following piece of code:
File: types.h
typedef struct Struct_A_T
{
int A;
char B;
float C;
}Struct_A;
File: code.c
#include "types.h"
void Function(const void *const ptr)
{
Struct_A localStruct = *((Struct_A *)ptr);
localStruct.A = 1000;
localStruct.B = 250;
localStruct.C = 128.485;
}
File: main.c
#include "types.h"
void Function(const void *const ptr);
int main(void)
{
Struct_A MyStruct1 = {2, 5, 2.8};
float local = 24.785;
/* Correct call */
Function(&MyStruct1);
/* Incorrect call!!! */
Function(&local);
}
And knowing that a pointer to void can be used as a "generic" pointer. How can I detect inside "Function" that the type passed in the void pointer is the correct in order to avoid the run time error provoked by the last call in the file main.c?
There's no way to do it using language features. It can only be done manually.
I, for one, use the following technique in debug builds of the code
typedef struct Struct_A_T
{
int A;
char B;
float C;
#ifdef DEBUG
unsigned signature;
#endif /* DEBUG */
}Struct_A;
i.e. in debug configuration I introduce an additional field into the structure. Each object of that struct type has to have that field initialized with some pre-determined "unpredictable" signature value specific for this type, like
#define STRUCT_A_SIGNATURE 0x12345678
which is easy to do if all structures are created in some centralized fashion (like allocated dynamically or initialized by a dedicated function). This might be more cumbersome if there's no such centralized location. But that the price we sometimes have to pay for safety. For example, in your example case that would be
Struct_A MyStruct1 = {2, 5, 2.8, 0x12345678 };
BTW, designated initializers might make such initializations more stable and it easier to read.
And then, in order to convert pointers from void * to the specific type I use the following cast macro
#ifdef DEBUG
#define TO_STRUCT_A(p)\
(assert((p) == NULL || ((Struct_A *)(p))->signature == STRUCT_A_SIGNATURE),\
(Struct_A *)(p))
#else /* DEBUG */
#define TO_STRUCT_A(p) ((Struct_A *)(p))
#endif /* DEBUG */
meaning that inside your Function you'd do
Struct_A localStruct = *TO_STRUCT_A(ptr);
which with very high probability will trigger assertion failure if a pointer to wrong type is passed to Function.
This all can (and should) be implemented using a more generic set of macros, of course.
Obviously, this only works for struct types, into which you can inject that additional signature field. Another potential problem with this approach is that by introducing an extra field into the structure in debug builds one can potentially cause the behavior of debug and release build to diverge.
You can't, that's the primary downside of void*, you have no way to determine what is being pointed to. You just have to know.
You may use sizeof to compare sizes of the struct to that which void* points points to. This is not a sufficient but necessary condition that a pointer to your struct type is passed to Function. BTW the property of languages with the possibility to check metadata (incl. types) of variables and wider is called reflection. It is available in many modern languages and some bits have been included recently in C++11, but C still lacks it.
So just for the sake if having ''fun'' I decided to emulate C++ member functions in C using pointer functions. Here is a simple code:
obj.h:
#ifndef OBJ_H
#define OBJ_H
#include <stdlib.h>
#include <stdio.h>
struct Obj{
struct pObjVar* pVar;
void (*read)(struct Obj*);
void (*set) (struct Obj*, int);
};
struct Obj* newObj();
void deleteObj(struct Obj** obj);
#endif
obj.c:
#include "obj.h"
void readValue(struct Obj* this_);
void setValue (struct Obj* this_, int mValue_);
struct pObjVar{
int mValue;
};
struct Obj* newObj(){
struct Obj* tmp = (struct Obj*) malloc(sizeof(struct Obj));
tmp->pVar = (struct pObjVar*) malloc(sizeof(struct pObjVar));
tmp->pVar->mValue = 0;
tmp->read = readValue;
tmp->set = setValue;
return tmp;
}
void deleteObj(struct Obj **obj){
free((*obj)->pVar); (*obj)->pVar = NULL;
free((*obj)); *obj = NULL;
}
void readValue(struct Obj *this_){
printf("Value = %d\n",this_->pVar->mValue);
}
void setValue(struct Obj *this_, int mValue_){
this_->pVar->mValue = mValue_;
}
main.c:
#include "obj.h"
int main(void)
{
struct Obj* a = newObj();
a->set(a, 10);
a->read(a);
deleteObj(&a);
return 0;
}
Output:
>./a.out
Value = 10
In doing this, however, I figured I had to emulate the role of implicit this pointer by explicitly passing it to my member functions. This works fine, I guess, except that it makes the whole thing look weird!
If I wanted to pass the object, why would implement the functions as member functions? The only answer I found to it was maybe in cases where you would want to have a unified interface but various implementations? (something similar to C++ virtual functions?)
What are (if any) some other reasons to emulate member functions? Also, is there any way to get around passing the explicit this_ pointer at all?
EDIT: There was problem in the original code when passing the object. I was using &a by mistake for the read/set functions. You would only need it for the deleteObj if you want to set the pointer to NULL internally.
Just another way of writing:
#define member(FUNC, ...) FUNC(this_, ## __VA_ARGS__)
int reader(struct Obj *_this) {
member(read, a, b, c);
member(getch);
return 0;
}
This can be used for implementing interfaces, inheritance and many C++ features, which were implemented like this in C with Classes times. In Linux kernel, file operations are implemented like this. File structure stores pointers to functions, so that each file system can store it's own system call handlers that operate on/with the data in the structure.
No, there is no way to do this automatically in C. The standard preprocessor is not competent enough to do the transformations.
There is also now way for a function to find out that it was called like a->func(10). Inside the function it is just func(10).
When Bjarne Stroustrup started designing C++, he wrote a special preprocessor/compiler Cfront for this.
In reality, C++ doesn't really store pointers to (non-virtual) functions. It just transforms a->set(10) to something like struct_Obj_set(a, 10) while compiling the code.