question
stringlengths
25
894
answer
stringlengths
4
863
I'm trying to read only the strings from an image file. I was able to successfully read all the strings in the image file using java. I wrapped the inputstream into a filereaderstream which is again wrapped inside of a bufferereader. so now i can extract all the strings from the image file (like xmp tags and exif, tiff tags etc) .. how do i accomplish the same thing using c. Thanks
If you are using unix based OS, you can use the (unix, not C) commandstrings.
im working on a c lib which would be nice to also work on embedded systems but im not very deep into embedded development so my question are most embedded compilers able to cope with local static variables - which i would then just assume in further development OR is there a #define which i can use for a #ifdef to create a global variable in case of thx
They should, as local static variables are part of the C standard. Of course, there is nothing preventing them from creating a C-like language that does not have all the features. But since that would be non-standard, then the way to identify that a feature is lacking would be non-standard as well.
Can anyone explain how @encode works to extract the datatype elements present in a given object, struct, or datatype into a type definition to be used as a class descriptor for instantiation? Or maybe a pointer to some resources for learning about the implementation of new preprocessor directives?
The@encodedirective parses the provided type and generates a constant string based on that type. The encoding of all C primitive types (including signed and unsigned versions) and the Objective-CidandSELtypes all have single-character encodings, these can be found in<objc/runtime.h>. More complicated types such asstructs and arrays have larger encodings. More information is available in theObjective-C Runtime Programming Guide[PDF].
I noticed that the boost library uses header files of (.hpp).I am curious since most source files I see use normal.hheader files.Could there be any special instances which warrant use of.hppinstead of.h? Thanks
Just convention, nothing special. You can use any extension on include files, actually.
I need to do a parse on the data written to my module, and the use of the strtok() function of string.h would be useful. However I've tried ``` #include <string.h> ``` and ``` #include <linux/string.h> ``` with no success. Is this possible? Or will I have to write my own strtok function? Thanks
The latest kernel library has this, which may do what you need: ``` /** * strsep - Split a string into tokens * @s: The string to be searched * @ct: The characters to search for * * strsep() updates @s to point after the token, ready for the next call. * * It returns empty tokens, too, behaving exactly like the libc function * of that name. In fact, it was stolen from glibc2 and de-fancy-fied. * Same semantics, slimmer shape. ;) */ ```
I am looking for an efficient algorithm in C to bitwise-transpose 8 bytes of data. What I mean with this is that if I have 8 bytes like this: ``` 00011100 00111000 00000001 00000000 11000000 00000000 11111111 01010101 ``` I want to get the following 8 bytes: ``` 00001010 00001011 01000010 11000011 11000010 10000011 00000010 00100011 ``` And since I want to use this on an embedded platform, it should be as fast as possible :-) All ideas are much appreciated!
SeeHacker's Delight, Chapter 7-3.
I have this code for a school assignment, but i can't manage to format it. When i run the program i keep getting 1.27768e-307. lp->price is a double with the value of 1000000.0000000000 ``` printf("Price of flat: %g\n", lp->price); ``` Any ideas? The other double values gets formatted correctly, just not price.
Please note that floating-point data types are really ill-suited for representing money. Then try: ``` printf("Price: %6f\n", lp->price); ``` The%fspecifier does not use scientific notation.
Assume I have a file pointerFILE* myfile. Is there a way to retrieve the name of the file wheremyfileis reading from or writing to?
Not in any CRT implementation that I've ever seen. It is useless info, you already have to supply the file name to get a FILE*. You could probably dig an operating system handle out of the FILE structure although you might need to hop through a file descriptor table. Your next problem is then the operating system support you'd need to map a file handle back to a file name. That should be difficult too.
I remember reading somewhere that it is better to use integers as loop counter variables rather than char or short. If yes, why? Does it provide any optimization benefits?
Generally, the compiler will makeintto be a good size for putting into one of your CPU's general purpose registers. That generally leads to fast access. Of course there's no guarantee of anything. The compiler is free to do a lot of things, including, I would guess, promote some of your code that usescharto some larger type. So the difference might not even matter. Really, for the answer that's true foryourcompiler, you should look at the assembly it outputs.
How would I go about making an array of file pointers in C?I would like to create an array of file pointers to the arguments of main... like a1.txt, a2.txt, etc... So I would run./prog arg1.txt arg2.txt arg3.txtto have the program use these files.Then the argument for main ischar **argv From argv, I would like to create the array of files/file pointers. This is what I have so far. ``` FILE *inputFiles[argc - 1]; int i; for (i = 1; i < argc; i++) inputFiles[i] = fopen(argv[i], "r"); ```
The code is fine, but remember to compile in C99. If you don't use C99, you need to create the array on heap, like: ``` FILE** inputFiles = malloc(sizeof(FILE*) * (argc-1)); // operations... free(inputFiles); ```
Could anybody please tell me what is the main difference between C & C++ structures.
In C++structandclassare the exact same thing, except for that struct defaults topublicvisibility and class defaults toprivatevisiblity. In C, struct names are in their own namespace, so if you havestruct Foo {};, you need to writestruct Foo foo;to create a variable of that type, while in C++ you can write justFoo foo;, albeit the C style is also permitted. C programmers usually usetypedef struct {} Foo;to allow the C++ syntax for variable definitions. The C programming language also does not support visibility restrictions, member functions or inheritance.
I am working with audio data. I'd like to play the sample file in reverse. The data is stored as unsigned ints and packed nice and tight. Is there a way to callmemcpythat will copy in reverse order. i.e. if I had 1,2,3,4 stored in an array, could I callmemcpyandmagicallyreverse them so I get 4,3,2,1.
No, memcpy won't do that backwards. If you're working in C, write a function to do it. If you're really working in C++ use std::reverse or std::reverse_copy.
I'm trying to import some c code into my c++ program. There are three lines that don't import directly: The first: ``` free(t); ``` The second: ``` new_node = (Tree *) malloc (sizeof (Tree)); ``` The third: ``` Tree * delete(int value, Tree * t) ``` How can these be changed to work in C++?
You can use free and malloc in C++. Whether you should is a different story, but if you're porting a C library the answer to that is yes (at least for now). deleteis a keyword in C++, you will need to rename that function.
I have this piece of code can you explain me the output ``` unsigned int x=3; ~x; printf("%d",x); ``` output is 10 I am not able to make it how. I have compiled the code on turbo c
The code as you've posted it won't compile. It will compile if you change~xtox = ~x;, but then it won't give the output "10". The~operator creates a bitwise inverse of the number given. In binary, the number 3 as an eight-bit integer is represented by the bits00000011. The~operator will replace every one of those bits with its opposite, giving11111100, which is 252 unsigned, or -4 signed. You declaredxas anunsigned int, which means a 32-bit unsigned value on most platforms. So your original value is00000000 00000000 00000000 00000011, and the inverse is11111111 11111111 11111111 11111100, or 4294967292.
While I was reading the reference about fopen function, I found out that FOPEN_MAX is a value that the "minimum number of streams that the implementation guarantees can be open simultaneously". Why it is the minimum number of streams? Doesn't it have to be "the maximum number of streams...." ?
Minimum number of streams that can be opened = guarantee that at least so many can be opened Maximum number of streams that can be opened = guarantee that opening any more will certainly fail What the wording means that if you have less than FOPEN_MAX streams open, it is guaranteed that at least one more can be opened, and the system does not necessarily provide any hard maximum
I found this in initramfs.c, I haven't seen this syntax before, could some one explain what it is doing? ``` static __initdata int (*actions[])(void) = { [Start] = do_start, [Collect] = do_collect, [GotHeader] = do_header, [SkipIt] = do_skip, [GotName] = do_name, [CopyFile] = do_copy, [GotSymlink] = do_symlink, [Reset] = do_reset, }; ``` Source Code (line 366):initramfs.c
This is an out-of-sequence array initialization by index. It's like writing ``` actions[Start] = do_start; actions[Collect] = do_collect; ``` except that you can do it as a static initializer.
Using visual studio 2008, I have an.Hand a.LIBfile of a library. I wrote a program and referenced the LIB via the project properties. It compiles fine, but when it runs, it asks for the DLL to be installed. If the DLL is in the same dir as theEXEit works but, if I have theLIB, doesn't it already mean the functions are statically linked to my program?
Not alllibfiles are static libraries. Some are import libraries, and chances are, that's what you linked with. If yourlibfile is much smaller than its correspondingdllfile, that's a sure sign that it's an import library.
I have a struct sockaddr and need to make a struct addrinfo (specifically that, because that's what some other API wants). The IP address may be IPv4 or IPv6. What's the best way to handle that?
Fromman 3 getaddrinfo, ``` struct addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; size_t ai_addrlen; struct sockaddr *ai_addr; char *ai_canonname; struct addrinfo *ai_next; }; ``` Astruct addrinfocontains more information than just astruct sockaddrdoes. Given astruct sockaddr_in, you can have some of this information (.ai_family = AF_INET, .ai_addrlen = sizeof(struct sockaddr_in)). Whether this is sufficient depends on what the other API is looking for.
While programming in C and GTK+, why is it "better" to useg_strdup_printf,g_free,g_strcmp0etc... and fellow GLib functions?
In general, GLib's purpose is a utility and portability library. Those in itself are reasons to consider using it. The specific functions you mention all offer something extra on top of their C standard library variants: g_strdup_printfis likesprintf, but actually allocates the buffer for you and saves you the guesswork of how large the buffer should be. (The return value should beg_free'd.)g_freeis likefree, but checks for a NULL-pointer.g_strcmp0is likestrcmp, but treats a NULL-pointer like an empty string, and thus sorts it in front.
i would like to know the function which returns the drive where the windows has been installed. for example if we run a program with following code in windows which is installed in "C:\" temp_char = getWindowsInstalledDrive(); should return "C:\". please point me to that function if you know. it should be a C/C++ function. Thanks.
You can use GetSystemDirectory():http://msdn.microsoft.com/en-us/library/ms724373%28VS.85%29.aspxand then take the first 3 letters.
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this question Let's say I have a simple config file that my c program needs to read/parse. Let's say it looks a little bit like this: ``` #Some comment key1=data1 key2=data2 ``` Is there a standard c lib that I can use instead of writing my own parser? Thanks Johan Note: Today I have my own little parser, but there must be some standard libs that solves this simple problem.
libconfigbut it does quite more than what you're asking
Yes, this is a really lazy question but I figure this is problem that people have often enough that someone here would have something already written to share. I have a ton of C files with#includestatements using Windows relative paths. I'm working on compiling the code on other operating systems (immediately, on my OS X development machine) and need to replace all the backslashes with forward slashes in these include statements. So, from something like#include "libs\helper.h"to#include "libs/helper.h".
``` sed '/^[ ]*#[ ]*include/ s:\\:/:g' ``` This should be pretty robust as it should catch any legal format of#includebut not anything else.
I'm trying to read only the strings from an image file. I was able to successfully read all the strings in the image file using java. I wrapped the inputstream into a filereaderstream which is again wrapped inside of a bufferereader. so now i can extract all the strings from the image file (like xmp tags and exif, tiff tags etc) .. how do i accomplish the same thing using c. Thanks
If you are using unix based OS, you can use the (unix, not C) commandstrings.
im working on a c lib which would be nice to also work on embedded systems but im not very deep into embedded development so my question are most embedded compilers able to cope with local static variables - which i would then just assume in further development OR is there a #define which i can use for a #ifdef to create a global variable in case of thx
They should, as local static variables are part of the C standard. Of course, there is nothing preventing them from creating a C-like language that does not have all the features. But since that would be non-standard, then the way to identify that a feature is lacking would be non-standard as well.
Can anyone explain how @encode works to extract the datatype elements present in a given object, struct, or datatype into a type definition to be used as a class descriptor for instantiation? Or maybe a pointer to some resources for learning about the implementation of new preprocessor directives?
The@encodedirective parses the provided type and generates a constant string based on that type. The encoding of all C primitive types (including signed and unsigned versions) and the Objective-CidandSELtypes all have single-character encodings, these can be found in<objc/runtime.h>. More complicated types such asstructs and arrays have larger encodings. More information is available in theObjective-C Runtime Programming Guide[PDF].
I noticed that the boost library uses header files of (.hpp).I am curious since most source files I see use normal.hheader files.Could there be any special instances which warrant use of.hppinstead of.h? Thanks
Just convention, nothing special. You can use any extension on include files, actually.
I need to do a parse on the data written to my module, and the use of the strtok() function of string.h would be useful. However I've tried ``` #include <string.h> ``` and ``` #include <linux/string.h> ``` with no success. Is this possible? Or will I have to write my own strtok function? Thanks
The latest kernel library has this, which may do what you need: ``` /** * strsep - Split a string into tokens * @s: The string to be searched * @ct: The characters to search for * * strsep() updates @s to point after the token, ready for the next call. * * It returns empty tokens, too, behaving exactly like the libc function * of that name. In fact, it was stolen from glibc2 and de-fancy-fied. * Same semantics, slimmer shape. ;) */ ```
I am looking for an efficient algorithm in C to bitwise-transpose 8 bytes of data. What I mean with this is that if I have 8 bytes like this: ``` 00011100 00111000 00000001 00000000 11000000 00000000 11111111 01010101 ``` I want to get the following 8 bytes: ``` 00001010 00001011 01000010 11000011 11000010 10000011 00000010 00100011 ``` And since I want to use this on an embedded platform, it should be as fast as possible :-) All ideas are much appreciated!
SeeHacker's Delight, Chapter 7-3.
I have this code for a school assignment, but i can't manage to format it. When i run the program i keep getting 1.27768e-307. lp->price is a double with the value of 1000000.0000000000 ``` printf("Price of flat: %g\n", lp->price); ``` Any ideas? The other double values gets formatted correctly, just not price.
Please note that floating-point data types are really ill-suited for representing money. Then try: ``` printf("Price: %6f\n", lp->price); ``` The%fspecifier does not use scientific notation.
Assume I have a file pointerFILE* myfile. Is there a way to retrieve the name of the file wheremyfileis reading from or writing to?
Not in any CRT implementation that I've ever seen. It is useless info, you already have to supply the file name to get a FILE*. You could probably dig an operating system handle out of the FILE structure although you might need to hop through a file descriptor table. Your next problem is then the operating system support you'd need to map a file handle back to a file name. That should be difficult too.
I remember reading somewhere that it is better to use integers as loop counter variables rather than char or short. If yes, why? Does it provide any optimization benefits?
Generally, the compiler will makeintto be a good size for putting into one of your CPU's general purpose registers. That generally leads to fast access. Of course there's no guarantee of anything. The compiler is free to do a lot of things, including, I would guess, promote some of your code that usescharto some larger type. So the difference might not even matter. Really, for the answer that's true foryourcompiler, you should look at the assembly it outputs.
How would I go about making an array of file pointers in C?I would like to create an array of file pointers to the arguments of main... like a1.txt, a2.txt, etc... So I would run./prog arg1.txt arg2.txt arg3.txtto have the program use these files.Then the argument for main ischar **argv From argv, I would like to create the array of files/file pointers. This is what I have so far. ``` FILE *inputFiles[argc - 1]; int i; for (i = 1; i < argc; i++) inputFiles[i] = fopen(argv[i], "r"); ```
The code is fine, but remember to compile in C99. If you don't use C99, you need to create the array on heap, like: ``` FILE** inputFiles = malloc(sizeof(FILE*) * (argc-1)); // operations... free(inputFiles); ```
Could anybody please tell me what is the main difference between C & C++ structures.
In C++structandclassare the exact same thing, except for that struct defaults topublicvisibility and class defaults toprivatevisiblity. In C, struct names are in their own namespace, so if you havestruct Foo {};, you need to writestruct Foo foo;to create a variable of that type, while in C++ you can write justFoo foo;, albeit the C style is also permitted. C programmers usually usetypedef struct {} Foo;to allow the C++ syntax for variable definitions. The C programming language also does not support visibility restrictions, member functions or inheritance.
I am working with audio data. I'd like to play the sample file in reverse. The data is stored as unsigned ints and packed nice and tight. Is there a way to callmemcpythat will copy in reverse order. i.e. if I had 1,2,3,4 stored in an array, could I callmemcpyandmagicallyreverse them so I get 4,3,2,1.
No, memcpy won't do that backwards. If you're working in C, write a function to do it. If you're really working in C++ use std::reverse or std::reverse_copy.
I'm trying to import some c code into my c++ program. There are three lines that don't import directly: The first: ``` free(t); ``` The second: ``` new_node = (Tree *) malloc (sizeof (Tree)); ``` The third: ``` Tree * delete(int value, Tree * t) ``` How can these be changed to work in C++?
You can use free and malloc in C++. Whether you should is a different story, but if you're porting a C library the answer to that is yes (at least for now). deleteis a keyword in C++, you will need to rename that function.
I have this piece of code can you explain me the output ``` unsigned int x=3; ~x; printf("%d",x); ``` output is 10 I am not able to make it how. I have compiled the code on turbo c
The code as you've posted it won't compile. It will compile if you change~xtox = ~x;, but then it won't give the output "10". The~operator creates a bitwise inverse of the number given. In binary, the number 3 as an eight-bit integer is represented by the bits00000011. The~operator will replace every one of those bits with its opposite, giving11111100, which is 252 unsigned, or -4 signed. You declaredxas anunsigned int, which means a 32-bit unsigned value on most platforms. So your original value is00000000 00000000 00000000 00000011, and the inverse is11111111 11111111 11111111 11111100, or 4294967292.
While I was reading the reference about fopen function, I found out that FOPEN_MAX is a value that the "minimum number of streams that the implementation guarantees can be open simultaneously". Why it is the minimum number of streams? Doesn't it have to be "the maximum number of streams...." ?
Minimum number of streams that can be opened = guarantee that at least so many can be opened Maximum number of streams that can be opened = guarantee that opening any more will certainly fail What the wording means that if you have less than FOPEN_MAX streams open, it is guaranteed that at least one more can be opened, and the system does not necessarily provide any hard maximum
I found this in initramfs.c, I haven't seen this syntax before, could some one explain what it is doing? ``` static __initdata int (*actions[])(void) = { [Start] = do_start, [Collect] = do_collect, [GotHeader] = do_header, [SkipIt] = do_skip, [GotName] = do_name, [CopyFile] = do_copy, [GotSymlink] = do_symlink, [Reset] = do_reset, }; ``` Source Code (line 366):initramfs.c
This is an out-of-sequence array initialization by index. It's like writing ``` actions[Start] = do_start; actions[Collect] = do_collect; ``` except that you can do it as a static initializer.
Using visual studio 2008, I have an.Hand a.LIBfile of a library. I wrote a program and referenced the LIB via the project properties. It compiles fine, but when it runs, it asks for the DLL to be installed. If the DLL is in the same dir as theEXEit works but, if I have theLIB, doesn't it already mean the functions are statically linked to my program?
Not alllibfiles are static libraries. Some are import libraries, and chances are, that's what you linked with. If yourlibfile is much smaller than its correspondingdllfile, that's a sure sign that it's an import library.
I have a struct sockaddr and need to make a struct addrinfo (specifically that, because that's what some other API wants). The IP address may be IPv4 or IPv6. What's the best way to handle that?
Fromman 3 getaddrinfo, ``` struct addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; size_t ai_addrlen; struct sockaddr *ai_addr; char *ai_canonname; struct addrinfo *ai_next; }; ``` Astruct addrinfocontains more information than just astruct sockaddrdoes. Given astruct sockaddr_in, you can have some of this information (.ai_family = AF_INET, .ai_addrlen = sizeof(struct sockaddr_in)). Whether this is sufficient depends on what the other API is looking for.
While programming in C and GTK+, why is it "better" to useg_strdup_printf,g_free,g_strcmp0etc... and fellow GLib functions?
In general, GLib's purpose is a utility and portability library. Those in itself are reasons to consider using it. The specific functions you mention all offer something extra on top of their C standard library variants: g_strdup_printfis likesprintf, but actually allocates the buffer for you and saves you the guesswork of how large the buffer should be. (The return value should beg_free'd.)g_freeis likefree, but checks for a NULL-pointer.g_strcmp0is likestrcmp, but treats a NULL-pointer like an empty string, and thus sorts it in front.
As the title, I'm finding vector/matrix library in C optimized for iPhone/iPod processors. Or just generally fast. ---(edit)--- I'm sorry for unclear question. I'm looking for fast lib for commercial games for iPhone/iPod. So GPL lib cannot be used. However, I'll stop finding fastest lib, it maybe meaningless.
Now(2010.06.26) Accelerate framework included on iOS4, so vDSP/BLAS functions are available. This utilizes hardware feature (CPU or SIMD) to accelerate floating point operations, so superior speed (2~4.5x average, 8x maximum) and less energy(0.25x maximum) consuming can be gained by using this. Thanks people for other answers.
I have a situation here i am taking input from user using scanf can I terminate the scanf as soon as user presses the # key please enlighten me on this
No,scanf()(or rather stdin, by default) is line-oriented so it needs to read a full line. Look intoncursesor similar libraries for "raw" key-by-key input.
How can I take a string (in this case it'll be loaded from a file) then remove certain characters and store them in an array. Ex: f.e.d.r.t.g.f remove "." to get f e d r t g f in an array where I can manipulate each individually
Just iterate through the string and only copy the characters you're interested in, maintaining an index of the current position in the new array.
How can I do this: ``` *(int *)CMSG_DATA(hdr) = fd2pass; ``` Without GCC raising this: ``` error: dereferencing type-punned pointer will break strict-aliasing rules ``` In a way compatible with these options: ``` -Wall -Werror -pedantic ```
Unless something is very wrong, there is no actual aliasing going on -- the object referred to by *(int *)CMSG_DATA(hdr) is not an alias for hdr -- it's past the end of hdr. The warning is incorrect. You can work around it with memcpy: ``` memcpy(CMSG_DATA(hdr), &fd2pass, sizeof(int)); ``` Don't use -fno-strict-aliasing: that disables optimizations that assume strict aliasing; it could generate considerably worse code. For technical details, seeglibc bug 16197.
I am making a little calculator in C, and i want to pass simple arithmetic formulae to my program. But it really does not like me passing character '*' to my program. Why not? And how can I work around this without changing the asterix to something else? Thanks
The character*is the shell's trigger for expanding matching filenames. There are several ways to deal with it: Escape it when typingmycalc 5 \* 3Place the whole expression in quotes and make sure the calculator's parser works that way:myprog "5 * 3"Don't use the command line: use your own input instead.
If C does not support passing a variable by reference, why does this work? ``` #include <stdio.h> void f(int *j) { (*j)++; } int main() { int i = 20; int *p = &i; f(p); printf("i = %d\n", i); return 0; } ``` Output: ``` $ gcc -std=c99 test.c $ a.exe i = 21 ```
Because you're passingthe valueof the pointer to the method and then dereferencing it to get the integer that is pointed to.
It's not possible to do something likefputs(4, fptOut);because fputs doesn't like integers. How can I work around this? Doingfputs("4", fptOut);is not an option because I'm working with a counter value.
What about ``` fprintf(fptOut, "%d", yourCounter); // yourCounter of type int in this case ``` Documentation offprintfcan be foundhere.
How can I read from the stdout of my program? One of my threads needs to access the stdout to read what the other threads are logging. I'm using the dear old plain C.
Make stdout use a pipe by replacing the stdout fd with the write side fd of apipeusingdup.
I want to archive my database of mysql. Kindly give me some guide lines how I can make it possible, I am using mysql c library for insertion and selection etc. I dont know how to use dump command.
UseSHOW TABLESandDESCRIBE tbl_namequeries to obtain structure of database and tables. Then, use SELECT to fetch data and proceed it to your output according to the structure.
I hear of a need to call assembly functions/calls when programming embedded systems in C. Is this necessary in C++ or not?
C++ does not provide any more low-level constructs than C does. Hence, if you need to fiddle around with control registers and ISRs in C, you will need to do it in C++.
I'm using a real time signal in Linux to be notified of the arrival of new data in a serial port. Unfortunately this causes sleep calls to be interrupted when there is signal. Does anybody know of a way to avoid this behavior? I tried using a regular signal (SIGUSR1) but I keep getting the same behavior.
From the nanosleep manpage: nanosleep delays the execution of the program for at least the time specified in *req. The function can return earlier if a signal has been delivered to the process. In this case, it returns -1, sets errno to EINTR, and writes the remaining time into the structure pointed to by rem unless rem is NULL. The value of *rem can then be used to call nanosleep again and complete the specified pause.
I came across this code for the binary representation of a number. I want to know the need for using !! in the code. ``` int main() { int n,i; unsigned flag = 1<<(sizeof(int) * 8 - 1); printf("Input the number\n"); scanf("%d",&n); for(i=0;i<sizeof(int)*8;i++) { printf("%d",!!(n & flag) ); n = n << 1; } return 0; } ```
!!will convert any non-zero value to 1, and leave zero value as zero. ``` x = 0; y = 50; !x; // 1 !y; // 0 !!x; // 0 !!y; // 1 ``` It is a poor man's bool cast.
Is there a way to replace any keyword in a text file using POSIX calls, without re creating the file.. If yes Please tell me how to do it.. Thanks in advance..
If the text and the replacement are the same size then you can open it with moder+, seek, and then write. If their sizes are different then there is no way to replace without recreating.
I've redirectedstdoutof a child process spawned withCreateProcessto a pipe. It works fine except that, as far as I can tell, no information about color changes are coming through. The child process is usingSetConsoleTextAttributeto change the text color--is it possible to detect this through the pipe and, if so, how? I'm ultimately displaying the output in aRichEditcontrol and I would like to capture the color information if at all possible. This is in C with the Win32 API on XP and Vista.
You probably need to use ReadConsoleOutput (and/or related ones) found here:http://msdn.microsoft.com/en-us/library/ms682073(VS.85).aspx. Hope that helps.
Hi I'm working in a Linux environment and I have to link to a object file already compiled which offers me some services (services.o) and I know some of them, but I'd like to know which are all of the exported symbols of it. Is there any way to accomplish this not having the sources? If so, how? Thanks you very much.
Trynm-- this tool is there for just this purpose.
I've been programming in .NET C# almost exclusively for the past 7 months or so. Before that, most of my programming had been in C++ (from school). At work, I will likely be needing to do a whole bunch of C in the next few months. Most of my exposure to C comes from micro-controllers and stuff I find on the internet. I understand the syntax and many of the difference between C and C++, but I don't really know what kind of built-in functions exist, what libraries I need to utilize to use said functions, and some memory management issues. Essentially I need to find some sort of quick crash course on C. Suggestions?
Write code. It's the only thing that works. Just pick any topic, and write some code.
I have been trying out some basic exercises involving loops. Can someone tell me why the following snippets have different outputs? While Loop ``` while (i<3) { while(j<3) { printf("(%d %d) ",i,j); j++; } i++; } ``` Output ``` (0 0) (0 1) (0 2) ``` For Loop ``` for(i=0;i<3;i++) { for(j=0;j<3;j++) printf("(%d %d) ",i,j); } ``` Output ``` (0 0) (0 1) (0 2) (1 0) (1 1) (1 2) (2 0) (2 1) (2 2) ``` Aren't they supposed to have the same output?
Try: ``` while (i<3) { j = 0; while(j<3) { printf("(%d %d) ",i,j); j++; } i++; } ``` In your code, what is happening is simple - for the first loop i = 0, j = 0, 1, 2, 3 for the second i = 1, j = 3...
Text is disappearing from the bottom of aRichEditcontrol window and I'd like to ensure the bottom character is always visible. Obviously, I could manually scroll to the bottom, but I'd like to do it under software control.
Send the EM_SCROLLCARET message. Position the caret first, GetWindowTextLength() and EM_SETSEL.
I have the compiler complaining (warning) about the folowing. Am I missing something? Because I thought this didn't need a cast ``` char* CurrentCh = some ptr value; int size; size = func(&CurrentCh); ``` with func defined like this ``` int func(void** ptr); ``` Compiler warning: passing argument 1 of 'func' from incompatible pointer type Thx
In C you can pass any pointer type to a function that expects a void*. What it says is "I need a pointer to something, it doesn't matter what it points to". Whereas void** says "I need a pointer to a void*, not a pointer to another pointer type".
If I have the following: ``` typedef struct _MY_STRUCT { int a; float b; } MY_STRUCT, *PMYSTRUCT ``` What does*PMYSTRUCTdo? Is it now a pointer type which I need to declare or just a pointer to_MY_STRUCTwhich I can use? I know thatMY_STRUCTis a new type that needs to be used as follows: ``` MY_STRUCT str; str.a = 2; ``` But what about that*PMYSTRUCT?
``` PMYSTRUCT ms = NULL; ``` is equal to ``` MYSTRUCT* ms = NULL; ```
I am fairly new to developing C/C++ code in MSVS but one of the things that has already confused me is why, after adding a set of source and header files to my project such that they show up respectively under the MSVS folders 'Source Files' and 'Header Files', do I subsequently have to tell the compiler where my header files are under 'Project->properties->C/C++->General'. It seems to me that MSVS should already attempt to resolve any 'include "..."' statements by first looking thru the set of header files I have included in the project. Anybody care to comment on the logic being used here? Thanks, Travis
The project files are used by the IDE to keep track of your files, but the compiler doesn't have access to that information. The include file path is passed to each source file when it compiles.
I direct you to Kernighan & Ritchie exercise 7.1 Write a program that converts upper case to lower case or lower case to upper case depending on the name it is invoked with,... How can I invoke the same program with different names? I am using Linux, so I am invoking a compiled program just by entering: $./a.out What should I be doing differently?
You should create a symbolic link, or just copy the executable of course: Either ``` $ ln -s a.out A.out ``` or ``` $ cp a.out A.out ``` Then in your program'smain(), inspectargv[0]to figure out how to act. This is a pretty useful technique, actually used often by production software.
I have this class with an instance method namedopenand need to call a function declared in C also calledopen. Follows a sample: ``` void SerialPort::open() { if(_open) return; fd = open (_portName.c_str(), O_RDWR | O_NOCTTY ); _open = true; } ``` When I try to compile it (using GCC) I get the following error: ``` error: no matching function for call to 'SerialPort::open(const char*, int)' ``` I included all the required C headers. When I change the name of the method for exampleopen2I don't have not problems compiling. How can I solve this problem. Thanks in advance.
Call ``` fd = ::open(_portName.c_str(), O_RDWR | O_NOCTTY ); ``` The double colon (::) before the function name is C++'sscope resolution operator: If the resolution operator is placed in front of the variable name then the global variable is affected.
In solaris how to detect broken socket in send() call? i dont want to use signal.i tried SO_NOSIGPIPE and MSG_NOSIGNAL but both are not available in Solaris and my program is getting killed with "broken pipe" error. Is there any way to detect broken pipe? Thanks!
You'll have to usesigaction()to specifically ignore theSIGPIPEsignal: ``` struct sigaction act; act.sa_handler = SIG_IGN; sigaction(SIGPIPE, &act, NULL); ``` ...thensend()will return -1 witherrnoset toEPIPE.
What would the equivalent in C/C++?
It's theCoCreateInstance()function. It is convenient to use CoCreateInstance when you need to create only a single instance of an object on the local machine. If you are creating an instance on remote computer, call CoCreateInstanceEx. When you are creating multiple instances, it is more efficient to obtain a pointer to the class object's IClassFactory interface and use its methods as needed. In the latter case, you should use the CoGetClassObject function. You'll need to #include <Objbase.h> and you'll need to link to ole32.lib
I work with satellite radar, and have been provided with a (very) large TIFF file containing 32 bpp greyscale data. Unfortunately,libtiff, the standard Linux library for working with TIFF files, doesn't support SampleFormat TIFF files, which means no support for high bit depth greyscale images or floating-point images. Does anyone know of a FOSS C library which provides support for these types of images? Failing that, can anyone suggest of an appropriate file format to convert to, and a FOSS library that can loadthat? (Ideally, it should be generally accepted by the scientific community for data interchange, and supported by IDL/ENVI).
Well libtiffshouldbe able to handle the format, although you may be limited to the low-level apis and doing the conversion to an image yourself. If the size of the images are >4Gb, there is bigtiff, a port of libtiff which handles extremely large images.
I'm programming in Windows right now, but portable code would be welcomed too. What I'm using right now isfwrite(4), but this function needs a maximum number of elements to be written to the file. I can usestrlen(1)here but I'd like to know if there is any better way to do this.
Usefputsinstead: ``` FILE * f = fopen( "myfile.txt", "w" ); fputs( "Hello world\n", f ); ```
Alright, I've cooked up some code to reverse hex characters around as part of a fun exercise I made up. Here is what I have at the moment: ``` #include <stdio.h> int main() { char a,b,c; while (1) { c = getchar(); if (!feof(stdin)) { a = c % 16; b = (c - a) / 16; c = (a*16) + b; putchar(c); }else{break;} } return 0; } ``` It works well for most values. For example, 0xA0 becomes 0x0A etc... However, it's not playing well with values beginning with 'F'. 0xF1 becomes 0x100xFF becomes 0xF0etc... Can somebody point me into the right direction?
If char is signed on your system, then when the upper nibble of c is f, c is negative, and c%16 will give a negative result.
I'm learning C right now and there is a conversion specifier %a which writes a number in p-notation as opposed to %e which writes something in e-notation (exponential notation). What is p-notation?
You use%ato get a hexadecimal representation of a floating-point number. This might be useful if you are a student learning floating-point representations, or if you want to be able to read and write anexactfloating-point number with no rounding error (but not very human-readable). This format specificier, along with many others, was added as part of the C99 standard. Dinkumware have anexcellent C99 library referencefree online; it's PJ Plauger's company, and he had a lot to do with both C89 and C99 standard libraries. Link above is to printing functions; the general library reference ishttp://www.dinkumware.com/manuals/default.aspx
sizeof(void*) and sizeof(function_type_ptr*) equality Must sizeof(void*) and sizeof(function_type_ptr*) be equal? Is it required by C (C90, C99) standard? function_type_ptr is pointer to function. This question is aboutstandard requirements, not your own opinion. Please, give links,section numbers and quotationsfrom standards
The answer is no. 6.2.6.1/2: Except for bit-fields, objects are composed of contiguous sequences of one or more bytes, the number, order, and encoding of which are either explicitly specified or implementation-defined. No such specification is done for function / void pointers.
I have experienced some strange behavior of Objective-C++. I have an Objective-C++ class, and it calls a classic C function in a method body. But linker cannot find the C function. I described the problem here:Xcode print symbol not found for my C function which used in Objective-C method body I solved the problem by changing Objective-C++ class to Objective-C class, but the question is still remained. Does it prohibited calling C function in Objective-C++ class?
You need to make sure that the C functions are declared ``` extern "C" ``` in the appropriate .h file. The common way of doing this is: ``` // // foo.h // #ifndef __FOO_H__ #define __FOO_H__ #ifdef __cplusplus extern "C" { #endif // ... your interface here - normal C function declarations etc ... #ifdef __cplusplus } #endif #endif ```
Let's say I have the following C code: ``` int main () { int *p = malloc(10 * sizeof *p); *p = 42; return 0; //Exiting without freeing the allocated memory } ``` When I compile and execute that C program, ie after allocating some space in memory, will that memory I allocated be still allocated (ie basically taking up space) after I exit the application and the process terminates?
It depends on the operating system. The majority of modern (and all major) operating systems will free memory not freed by the program when it ends. Relying on this is bad practice and it is better to free it explicitly. The issue isn't just that your code looks bad. You may decide you want to integrate your small program into a larger, long running one. Then a while later you have to spend hours tracking down memory leaks.Relying on a feature of an operating system also makes the code less portable.
I came across this code for the binary representation of a number. I want to know the need for using !! in the code. ``` int main() { int n,i; unsigned flag = 1<<(sizeof(int) * 8 - 1); printf("Input the number\n"); scanf("%d",&n); for(i=0;i<sizeof(int)*8;i++) { printf("%d",!!(n & flag) ); n = n << 1; } return 0; } ```
!!will convert any non-zero value to 1, and leave zero value as zero. ``` x = 0; y = 50; !x; // 1 !y; // 0 !!x; // 0 !!y; // 1 ``` It is a poor man's bool cast.
Is there a way to replace any keyword in a text file using POSIX calls, without re creating the file.. If yes Please tell me how to do it.. Thanks in advance..
If the text and the replacement are the same size then you can open it with moder+, seek, and then write. If their sizes are different then there is no way to replace without recreating.
I've redirectedstdoutof a child process spawned withCreateProcessto a pipe. It works fine except that, as far as I can tell, no information about color changes are coming through. The child process is usingSetConsoleTextAttributeto change the text color--is it possible to detect this through the pipe and, if so, how? I'm ultimately displaying the output in aRichEditcontrol and I would like to capture the color information if at all possible. This is in C with the Win32 API on XP and Vista.
You probably need to use ReadConsoleOutput (and/or related ones) found here:http://msdn.microsoft.com/en-us/library/ms682073(VS.85).aspx. Hope that helps.
Hi I'm working in a Linux environment and I have to link to a object file already compiled which offers me some services (services.o) and I know some of them, but I'd like to know which are all of the exported symbols of it. Is there any way to accomplish this not having the sources? If so, how? Thanks you very much.
Trynm-- this tool is there for just this purpose.
I've been programming in .NET C# almost exclusively for the past 7 months or so. Before that, most of my programming had been in C++ (from school). At work, I will likely be needing to do a whole bunch of C in the next few months. Most of my exposure to C comes from micro-controllers and stuff I find on the internet. I understand the syntax and many of the difference between C and C++, but I don't really know what kind of built-in functions exist, what libraries I need to utilize to use said functions, and some memory management issues. Essentially I need to find some sort of quick crash course on C. Suggestions?
Write code. It's the only thing that works. Just pick any topic, and write some code.
I have an array of data that represents PNG: ``` unsigned short systemFontTexture[] = { ... 0x5089,0x474E,0x0A0D,0x5089,0x474E,0x0A0D,0x5089, 0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089, 0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089, ... } ``` Can I create PNG file using this data? If yes, then HOW?
Create a data providerto serve up the data, and thencreate an image with the data provider.
Can I mix extern and const, asextern const? If yes, does theconstqualifier impose it's reign only within the scope it's declared in or should it exactly match the declaration of the translational unit it's declared in? I.e. can I declare sayextern const int i;even when the actualiis not a const and vice versa?
Yes, you can use them together.And yes, it should exactly match the declaration in the translation unit it's actually declared in. Unless of course you are participating in theUnderhanded C Programming Contest:-) The usual pattern is: file.h:extern const int a_global_var;file.c:#include "file.h"const int a_global_var = /* some const expression */; Edit: Incorporated legends2k's comment. Thanks.
I am preparing myself for a lecture exam on security aspects of software development. I would like to know if it is always possible to read the value of a static char array from a binary with hexdump? If not on what factors does it depend whether I can read the value of it or not with a hexeditor?? thanks,
If you can locate the variable in the memory, you can read it with a hexdump - that's what hexdump programs are for. How easy it is to locate depends on how much information you have about the binary and on what you know about its expected contents.
I have one static variable declared inside a function, which is not initialized to zero explicitly. Are all uninitialized static variables inside functions set to zero by default, just as static variables at the global (file) level are?
All static variables without an explicit initializer are initialized to zero. All the variables going into theBSSsegment are initialized to zero. In C, all global and static variables without an explicit initializer go into the BSS segment and hence are zero by default.
One of the only languages that compiles to a high level language such as C, Vala has interested me for quite a bit. I've been wanting to start a small project with it, but I've been wondering how I would distribute it. The fact is, that it compiles to C code (C99 I suppose). Can I distribute the C code instead of the Vala code?If I do, is the C code compatible with all platforms?Or does it, for example when using sockets, include the appropriate stuff (winsock.h for Windows) automatically?
From a Vala developer in irc, #vala on irc.gnome.org: ``` 18:57 < flo> It is of course possible to distribute the C code as well. The compiler itself is shiped with vala and C code. We actually access C-libraries over an abstract interface with all advantages and disadvantages of the libraries we are using, including platform dependencies. ```
can someone explain to me why the following results in b = 13? ``` int a, b, c; a = 1|2|4; b = 8; c = 2; b |= a; b&= ~c; ```
It is using binary manipultaors. (Assuming ints are 1 byte, and use Two's complement for storage, etc.) a = 1|2|4meansa = 00000001 or 00000010 or 00000100, which is 00000111, or 7.b = 8meansb = 00001000.c = 2meansc = 00000010.b |= ameansb = b | awhich meansb = 00001000 or 00000111, which is 00001111, or 15.~cmeansnot c, which is 11111101.b &= ~cmeansb = b & ~c, which meansb = 00001111 and 11111101, which is 00001101, or 13.
I have the following struct: ``` struct cell { int nmbr; struct cell *p; }; ``` I have created a chain of linked structs from this type. Every struct is connected to its predecessor through *p. If I decide to print allnmbrs with a recursive algorithm as shown below, how do I define the stop condition? ``` void write(struct cell* l) { /* The following if statement doesn't solve my problem, but hopefully you see what I'm trying to do */ if (&l != 0x000000) { printf("%d \t", l->nmbr); write(l->p); } } ```
You want ``` if (l != 0) ``` or ``` if (l != NULL) ``` Of course, you also need to make sure that the tail of your linked list haspassignedNULLas well; otherwise it will be uninitialized and probably something notNULLbut invalid anyway.
How do I set the modification time of a file programmatically in Windows?
From:http://rosettacode.org/wiki/File/Modification_Time#C ``` #include <time.h> #include <utime.h> #include <sys/stat.h> const char *filename = "input.txt"; int main() { struct stat foo; time_t mtime; struct utimbuf new_times; stat(filename, &foo); mtime = foo.st_mtime; /* seconds since the epoch */ new_times.actime = foo.st_atime; /* keep atime unchanged */ new_times.modtime = time(NULL); /* set mtime to current time */ utime(filename, &new_times); return 0; } ```
This question already has answers here:Closed13 years ago. Possible Duplicates:[C] Header per source file.In C++ why have header files and cpp files?C++ - What should go into an .h file? Is the only reason header files exist in Cso a developer can quickly see what functions are availableand what arguments they can take? Or is it something to do with the compiler? Why has no other language used this method? Is it just me, or does it seem that having 2 sets of function definitionswill only lead to more maintenance and more room for errors? Or is knowing about header files just something every C developer must know?
Header files are needed todeclarefunctions and variables that are available. You might not have access to the definitions (=the .c files)at all; C supports binary-only distribution of code in libraries.
``` #include <stdio.h> #include <stdlib.h> typedef int element; struct cell { element e; struct cell *p; }; typedef struct cell* CELL; int main() { CELL* p; p = (CELL*) malloc (sizeof(struct cell)); p->e = 8; /* This ain't working */ *p.e = 8; /* This doesn't help anything either */ return 0; } ``` I'm just getting started withmallocand I just made a pointer to a newly createdCELL, which is astruct. Now I'm trying to fill it with some values, but I'm greeted by an unfriendly "request for member e" in something not a structure or union". I did make a pointer to astructthat contains a member called e, or at least that's what I think I did. Why does this fail?
I think this nicely illustrates a rule of good C style - do not create typedefs that hide the fact that something is a pointer.
I've just started learning C on Mac OS X. I have downloaded Xcode too. So far, I have been typing my apps into TextEdit, and then using the Terminal to locate my apps and compile them usinggcc hello.cetc. Is there an easier way (using Xcode perhaps?) to type my code into some form of IDE, and then automate the compiling with a 'compile and run' button or similiar? It seems a bit primitive and tedious using TextEdit and then switching to the Terminal to compile. However, I do not have much experience with lower level languages like C, so I'm unsure if it is even possible. Thanks
Yes that is what XCode is for. Look at the tutorial on the open screen of XCode (version 3.2.1 for OSX 10.6) This is for objective C but the tools are the same. Or if the objective C is confusing choose a new project from XCode. File->New Project) choose command line tool as the project type and then choose type as C from the pop up menu
How can I detect when a removable disk drive is (dis)connected to the system? How to get the mount path (for Linux) and the drive letter (for windows)? EDIT: Is there a way to detect the currently connected devices?
For Windows, the APIRegisterDeviceNotificationwill let you know when a USB device is added. The information about the volume is given in theDEV_BROADCAST_VOLUME structure. Thedbcv_unitmaskgives the drive letter.
``` #define STRMAX 50 struct Person { char sName[STRMAX]; int iAge; }; typedef struct Person PERSON; int main() { PERSON *personen[1]; personen[0]->sName = "Pieter"; personen[0]->iAge = 18; return 0; } ``` This code generates an error onpersonen[0]->sName = "Pieter";sayingincompatible types in assignment. Why?
You don't want an array of pointers. TryPERSON personen[1]; And like others have said, use the strcpy function!
I have an array of data that represents PNG: ``` unsigned short systemFontTexture[] = { ... 0x5089,0x474E,0x0A0D,0x5089,0x474E,0x0A0D,0x5089, 0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089, 0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089, ... } ``` Can I create PNG file using this data? If yes, then HOW?
Create a data providerto serve up the data, and thencreate an image with the data provider.
Can I mix extern and const, asextern const? If yes, does theconstqualifier impose it's reign only within the scope it's declared in or should it exactly match the declaration of the translational unit it's declared in? I.e. can I declare sayextern const int i;even when the actualiis not a const and vice versa?
Yes, you can use them together.And yes, it should exactly match the declaration in the translation unit it's actually declared in. Unless of course you are participating in theUnderhanded C Programming Contest:-) The usual pattern is: file.h:extern const int a_global_var;file.c:#include "file.h"const int a_global_var = /* some const expression */; Edit: Incorporated legends2k's comment. Thanks.
I am preparing myself for a lecture exam on security aspects of software development. I would like to know if it is always possible to read the value of a static char array from a binary with hexdump? If not on what factors does it depend whether I can read the value of it or not with a hexeditor?? thanks,
If you can locate the variable in the memory, you can read it with a hexdump - that's what hexdump programs are for. How easy it is to locate depends on how much information you have about the binary and on what you know about its expected contents.
I have one static variable declared inside a function, which is not initialized to zero explicitly. Are all uninitialized static variables inside functions set to zero by default, just as static variables at the global (file) level are?
All static variables without an explicit initializer are initialized to zero. All the variables going into theBSSsegment are initialized to zero. In C, all global and static variables without an explicit initializer go into the BSS segment and hence are zero by default.
One of the only languages that compiles to a high level language such as C, Vala has interested me for quite a bit. I've been wanting to start a small project with it, but I've been wondering how I would distribute it. The fact is, that it compiles to C code (C99 I suppose). Can I distribute the C code instead of the Vala code?If I do, is the C code compatible with all platforms?Or does it, for example when using sockets, include the appropriate stuff (winsock.h for Windows) automatically?
From a Vala developer in irc, #vala on irc.gnome.org: ``` 18:57 < flo> It is of course possible to distribute the C code as well. The compiler itself is shiped with vala and C code. We actually access C-libraries over an abstract interface with all advantages and disadvantages of the libraries we are using, including platform dependencies. ```
can someone explain to me why the following results in b = 13? ``` int a, b, c; a = 1|2|4; b = 8; c = 2; b |= a; b&= ~c; ```
It is using binary manipultaors. (Assuming ints are 1 byte, and use Two's complement for storage, etc.) a = 1|2|4meansa = 00000001 or 00000010 or 00000100, which is 00000111, or 7.b = 8meansb = 00001000.c = 2meansc = 00000010.b |= ameansb = b | awhich meansb = 00001000 or 00000111, which is 00001111, or 15.~cmeansnot c, which is 11111101.b &= ~cmeansb = b & ~c, which meansb = 00001111 and 11111101, which is 00001101, or 13.
I have the following struct: ``` struct cell { int nmbr; struct cell *p; }; ``` I have created a chain of linked structs from this type. Every struct is connected to its predecessor through *p. If I decide to print allnmbrs with a recursive algorithm as shown below, how do I define the stop condition? ``` void write(struct cell* l) { /* The following if statement doesn't solve my problem, but hopefully you see what I'm trying to do */ if (&l != 0x000000) { printf("%d \t", l->nmbr); write(l->p); } } ```
You want ``` if (l != 0) ``` or ``` if (l != NULL) ``` Of course, you also need to make sure that the tail of your linked list haspassignedNULLas well; otherwise it will be uninitialized and probably something notNULLbut invalid anyway.
How do I set the modification time of a file programmatically in Windows?
From:http://rosettacode.org/wiki/File/Modification_Time#C ``` #include <time.h> #include <utime.h> #include <sys/stat.h> const char *filename = "input.txt"; int main() { struct stat foo; time_t mtime; struct utimbuf new_times; stat(filename, &foo); mtime = foo.st_mtime; /* seconds since the epoch */ new_times.actime = foo.st_atime; /* keep atime unchanged */ new_times.modtime = time(NULL); /* set mtime to current time */ utime(filename, &new_times); return 0; } ```
This question already has answers here:Closed13 years ago. Possible Duplicates:[C] Header per source file.In C++ why have header files and cpp files?C++ - What should go into an .h file? Is the only reason header files exist in Cso a developer can quickly see what functions are availableand what arguments they can take? Or is it something to do with the compiler? Why has no other language used this method? Is it just me, or does it seem that having 2 sets of function definitionswill only lead to more maintenance and more room for errors? Or is knowing about header files just something every C developer must know?
Header files are needed todeclarefunctions and variables that are available. You might not have access to the definitions (=the .c files)at all; C supports binary-only distribution of code in libraries.