question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
It's common for compilers to provide aswitch to warn when code is unreachable. I've also seen macros for some libraries, that provideassertions for unreachable code.
Is there a hint, such as through a pragma, or builtin that I can pass to GCC (or any other compilers for that matter), that will warn or error during compilation if it's determined that a line expected to be unreachable can actually be reached?
Here's an example:
```
if (!conf->devpath) {
conf->devpath = arg;
return 0;
} // pass other opts into fuse
else {
return 1;
}
UNREACHABLE_LINE();
```
The value of this is in detecting, after changes in conditions above the expected unreachable line, that the line is in fact reachable.
|
gcc 4.5 supports the__builtin_unreachable()compiler inline, combining this with-Wunreachable-codemight do what you want, but will probably cause spurious warnings
|
How do I define macros on a per-project, or per file level in a C project using autotools?
Presently I have this:mount_cpfs_CPPFLAGS = -DFUSE_USE_VERSION=28, but I'm not sure that this is the "portable" way to define a C macro.
|
Consider using generated header files withAC_DEFINE.
|
I have my own, very fast cos function:
```
float sine(float x)
{
const float B = 4/pi;
const float C = -4/(pi*pi);
float y = B * x + C * x * abs(x);
// const float Q = 0.775;
const float P = 0.225;
y = P * (y * abs(y) - y) + y; // Q * y + P * y * abs(y)
return y;
}
float cosine(float x)
{
return sine(x + (pi / 2));
}
```
But now when I profile, I see that acos() is killing the processor. I don't need intense precision. What is a fast way to calculate acos(x)
Thanks.
|
A simple cubic approximation, the Lagrange polynomial for x ∈ {-1, -½, 0, ½, 1}, is:
```
double acos(x) {
return (-0.69813170079773212 * x * x - 0.87266462599716477) * x + 1.5707963267948966;
}
```
It has a maximum error of about 0.18 rad.
|
I'm working on implementing bezier handles into my application. I have points and I need to figure out weather the current direction of the new point is clockwise or counter clockwise. This is because my bezier interpolation algorithm calculates the handles from right to left.
Therefore no matter what it interpolates:
P1 P1.righthandle P2 P2.lefthandle to achieve cubic bezier
How can I figure out if the shape is CW or CCW. Thanks
|
You have your original angle, the last known angle (since I'm sure you're redrawing the handle as it's being dragged), and the current angle. I'd take a look at the last known handle angle on the last redraw and compare whether the new angle, relative to that is > 180 degrees or < 180 degrees. If it's 0 - 180 degrees, it's moving in a clockwise direction, and if it's 180 - 360 degrees, it's moving in a counterclockwise direction.
|
This applies to several cases in my application:
I have 3 or 4 functions that belong together, one is a starting function that creates and frees the required memory structures and calls the other functions as appropriate. The other functions also call themselves repeatedly. Only the starting functions is called from outside, and only once or not at all per application-run.
Currently, I pass pointers to the memory structures from the starting function as function arguments, but the argument list is getting quite long in some cases.
Is there any argument against creating classes for all these cases and making the pointers to the memory structures members?
|
Definitely go for a class here. That's what objects and classes are designed for.
|
It's common for compilers to provide aswitch to warn when code is unreachable. I've also seen macros for some libraries, that provideassertions for unreachable code.
Is there a hint, such as through a pragma, or builtin that I can pass to GCC (or any other compilers for that matter), that will warn or error during compilation if it's determined that a line expected to be unreachable can actually be reached?
Here's an example:
```
if (!conf->devpath) {
conf->devpath = arg;
return 0;
} // pass other opts into fuse
else {
return 1;
}
UNREACHABLE_LINE();
```
The value of this is in detecting, after changes in conditions above the expected unreachable line, that the line is in fact reachable.
|
gcc 4.5 supports the__builtin_unreachable()compiler inline, combining this with-Wunreachable-codemight do what you want, but will probably cause spurious warnings
|
How do I define macros on a per-project, or per file level in a C project using autotools?
Presently I have this:mount_cpfs_CPPFLAGS = -DFUSE_USE_VERSION=28, but I'm not sure that this is the "portable" way to define a C macro.
|
Consider using generated header files withAC_DEFINE.
|
I have my own, very fast cos function:
```
float sine(float x)
{
const float B = 4/pi;
const float C = -4/(pi*pi);
float y = B * x + C * x * abs(x);
// const float Q = 0.775;
const float P = 0.225;
y = P * (y * abs(y) - y) + y; // Q * y + P * y * abs(y)
return y;
}
float cosine(float x)
{
return sine(x + (pi / 2));
}
```
But now when I profile, I see that acos() is killing the processor. I don't need intense precision. What is a fast way to calculate acos(x)
Thanks.
|
A simple cubic approximation, the Lagrange polynomial for x ∈ {-1, -½, 0, ½, 1}, is:
```
double acos(x) {
return (-0.69813170079773212 * x * x - 0.87266462599716477) * x + 1.5707963267948966;
}
```
It has a maximum error of about 0.18 rad.
|
I'm working on implementing bezier handles into my application. I have points and I need to figure out weather the current direction of the new point is clockwise or counter clockwise. This is because my bezier interpolation algorithm calculates the handles from right to left.
Therefore no matter what it interpolates:
P1 P1.righthandle P2 P2.lefthandle to achieve cubic bezier
How can I figure out if the shape is CW or CCW. Thanks
|
You have your original angle, the last known angle (since I'm sure you're redrawing the handle as it's being dragged), and the current angle. I'd take a look at the last known handle angle on the last redraw and compare whether the new angle, relative to that is > 180 degrees or < 180 degrees. If it's 0 - 180 degrees, it's moving in a clockwise direction, and if it's 180 - 360 degrees, it's moving in a counterclockwise direction.
|
This applies to several cases in my application:
I have 3 or 4 functions that belong together, one is a starting function that creates and frees the required memory structures and calls the other functions as appropriate. The other functions also call themselves repeatedly. Only the starting functions is called from outside, and only once or not at all per application-run.
Currently, I pass pointers to the memory structures from the starting function as function arguments, but the argument list is getting quite long in some cases.
Is there any argument against creating classes for all these cases and making the pointers to the memory structures members?
|
Definitely go for a class here. That's what objects and classes are designed for.
|
I follow this PJLIB (https://trac.pjsip.org/repos/wiki/Getting-Started/Autoconf). But i cant get this up yet, always its giving undefined reference, can anyone please have a look kindly.
Stackoverlow source code gets broken please find from
here details:http://gist.github.com/5765529
```
[sun@example mysip]$ gcc myapp.c
/tmp/ccEKxwjG.o: In function `main':
myapp.c:(.text+0xa): undefined reference to `pjsua_create'
collect2: ld returned 1 exit status
```
Thank you
|
You are not linking with the library. You need something like:
```
gcc myapp.c -lpjlib
```
but exactly what you need I don't know - it will be described in the library's documentation.
|
I need to sleep my program in Windows. What header file has the sleep function?
|
Use:
```
#include <windows.h>
Sleep(sometime_in_millisecs); // Note uppercase S
```
And here's a small example that compiles withMinGWand does what it says on the tin:
```
#include <windows.h>
#include <stdio.h>
int main() {
printf( "starting to sleep...\n" );
Sleep(3000); // Sleep three seconds
printf("sleep ended\n");
}
```
|
In Visual C++, it's possible to use#pragma warning (disable: ...). Also I found that in GCC you canoverride per file compiler flags. How can I do this for "next line", or with push/pop semantics around areas of code using GCC?
|
It appears thiscan be done. I'm unable to determine the version of GCC that it was added, but it was sometime before June 2010.
Here's an example:
```
#pragma GCC diagnostic error "-Wuninitialized"
foo(a); /* error is given for this one */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
foo(b); /* no diagnostic for this one */
#pragma GCC diagnostic pop
foo(c); /* error is given for this one */
#pragma GCC diagnostic pop
foo(d); /* depends on command line options */
```
|
What does this GCC warning mean?
```
cpfs.c:232:33: warning: ISO C99 requires rest arguments to be used
```
The relevant lines are:
```
__attribute__((format(printf, 2, 3)))
static void cpfs_log(log_t level, char const *fmt, ...);
#define log_debug(fmt, ...) cpfs_log(DEBUG, fmt, ##__VA_ARGS__)
log_debug("Resetting bitmap");
```
The last line being line 232 inside a function implementation. The compiler flags are:
```
-g -Wall -std=gnu99 -Wfloat-equal -Wuninitialized -Winit-self -pedantic
```
|
Yes it means that you have to pass at least two arguments the way that you defined it. You could just do
```
#define log_debug(...) cpfs_log(DEBUG, __VA_ARGS__)
```
and then you'd also avoid the gcc extension of the, ##construct.
|
I have a Perl program and a C program. I want to run the Perl program and capture the return value of C program. To make it clear:
C program (a.out)
```
int main()
{
printf("100");
return 100;
}
```
Perl program:
```
print `ls`; #OK
print `a.out`; #No error but it does not print any output.
```
Any ideas?
Thanks.
|
I don't know perl but this works on my system so no guarantees:
```
#!/usr/bin/perl
print "Running a.out now\n";
$exitCode = system("./a.out");
print "a.out returned:\n";
print $exitCode>>8; print "\n";
```
For one reason or anothersystem()returns the return value bitshfted by 8 (so 0 will become 256, 1 will be 512... 7 will be 1792 or something like that) but I didn't care to look up why.
|
I have written a C CGI executable, and I want it to be able to retrieve the PATH_INFO from Apache. For example, if I have the compiled C file as /var/www/html/file, and I requesthttp://localhost/file/pathinfo, How do I get the pathinfo portion?
If you have any idea, please help. Thanks in advance!
|
This (and a great deal of other information) is available as environment variables. This shell script, run as a CGI script in your environment, will dump everything you can get at:
```
#! /bin/sh
printf "Content-Type: text/plain\n\n"
printenv
```
From your C program, access the variables usinggetenv()as usual.
|
Can I add a systemcall from a module?
|
In some kernel versions it is possible to add or modify asystemcallby changing the sys_call_table. But because this table is not intended to be changed at runtime, it has no protection. Changing the table will lead to race conditions. Even without the race conditions, there are problems related to removing the modules while they are in use or stacked. Because of the problems with changingsys_call_tablefrom modules, the symbol is no longer exported in new kernels. In other words if you get"unresolved symbol sys_call_table"when trying to load a module, it means there is a bug in the module, and the kernel does no longer accept such buggy modules.
|
I have a C dll containing functions and enumerations I want to make accessible from php.
How can I do it?
|
You need to write an extension. You do need some C experience butthis tutorialis pretty easy to follow.
editI googled around out of curiosity, apparently you can sort-of dynamically load a dll from php usingw32api. I'd still go for the extension ;-)
|
My application produces strings like the one below. I need to parse values between the separator into individual values.
```
2342|2sd45|dswer|2342||5523|||3654|Pswt
```
I am usingstrtokto do this in a loop. For the fifth token, I am getting 5523. However, I need to account for the empty value between the two separators||as well. 5523 should be the sixth token, as per my requirement.
```
token = (char *)strtok(strAccInfo, "|");
for (iLoop=1;iLoop<=106;iLoop++) {
token = (char *)strtok(NULL, "|");
}
```
Any suggestions?
|
In that case I often prefer ap2 = strchr(p1, '|')loop with amemcpy(s, p1, p2-p1)inside. It's fast, does not destroy the input buffer (so it can be used withconst char *) and is really portable (even on embedded).
It's also reentrant;strtokisn't. (BTW: reentrant has nothing to do with multi-threading.strtokbreaks already with nested loops. One can usestrtok_rbut it's not as portable.)
|
Is it possible to pass settimeofday() my time_t/epoch time value, in C? Could someone give me an example of how I could do it ... my C skills are a little rusty :S
Would it be:
```
time_t time = somevalue;
settimeofday(somevalue, NULL);
```
I don't have admin access where I'm working and so can't test it out.
Thanks in advance!
|
settimeofday() takes astruct timeval *as first argument, so you should do
```
struct timeval tv;
tv.tv_sec = somevalue;
tv.tv_usec = 0;
settimeofday(&tv,NULL);
```
followup editgettimeofday() is the counterpart:
```
struct timeval tv;
if ( !gettimeofday(&tv,NULL) ) // *always* check return values ;-)
{
long long microsince1970;
microsince1970 = tv.tv_sec*1000000 + tv.tv_usec;
printf("it's been %lld µs ago\n",microsince1970);
}
```
|
Since C99 (and C++20), it's possible to initialize structs using this syntax:
```
struct info
{
char name[8+1];
int sz;
int typ;
};
struct info arr[] =
{
[0] = { .sz = 20, .name = "abc" },
[9] = { .sz = -1, .name = "" }
};
```
What happens to the unspecified fields?
|
They are zeroed. From the C99 standard §6.7.8 (Initialization)/21,
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array,the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
|
Can anyone tell me how I can create a basic usable Windows application in C (I have a little idea about C++ also) ?
|
Get Petzold'sProgramming Windowsbook; it's a classic and covers Win32 development from its core C roots.
|
I have a C++ application which connects to a MySQL server.It all works fine.
Currently it uses libmysql.dll.At build time I link to libmysql.lib.
As far as I understand I can link to mysqlclient.lib instead and get rid of the dependency of libmysql.dll, i.e have the functionality embedded within my exe.
My question is:Where can I find the source to build mysqlclient.lib?
When debugging the app when it's linked to mysqlclient.lib and stepping into mysql_library_init() for example the debugger (VC++ 2008) asks for the file "f:\build\mysql-5.0.67-winbuild\mysql-community-nt-5.0.67-build\libmysql\libmysql.c".
Note: libmysql.lib & mysqlclient.lib are included in the installation of MySQL.
|
IIRC, it's a part of the MySQL source code:http://dev.mysql.com/downloads/mysql/#downloads
|
I have this program execute with the values 10,20,30 given at command line.
```
int main(int argc , char **argv)
{
printf("\n Printing the arguments of a program \n");
printf("\n The total number of arguments in the program is %d",argc);
while(argc>=0)
{
printf("%s ",argv[argc]);
argc--;
}
return 0;
}
```
The outputs is
The total number of arguments in the program is 4(null) 30 20 10 ./a.out
Where did that (null) come from ??
|
argv[0]is (to the extent possible) supposed to be something that identifies the program being run.argv[1]throughargv[argc-1]are the arguments that were actually entered on the command line.argv[argc]is required to be a null pointer (§5.1.2.2.1/2).
|
How can I capture screen and save it as am image in C?OS: windows (XP & Seven)
Thanks
|
Have you triedgoogle? Thisforum entryhas an example, complete with C source code using the Win32 API.
EDIT: Found a duplicate in the meantime:How can I take a screenshot and save it as JPEG on Windows?
|
I need a utility to check conflicts in header guards. It would be nice if the utility could check if symbols and file names are consistent (using regex or something).
Regards,
rn141.
EDIT:
Example 1. Broken header guard. Doesn't protect from multiple inclusion.
```
// my_file1.h
#ifndef my_project_my_file1_h__
#define my_project_my_fil1_h__ // should be my_project_my_file1_h__
// code goes here
#endif
```
Example 2. Conflicts with the above header guard.
```
// my_file2.h
#ifndef my_project_my_file1_h__ // should be my_project_my_file2_h__
#define my_project_my_file1_h__ // should be my_project_my_file2_h__
// code goes here
#endif
```
|
How about using#pragma onceinstead?
|
For example
```
sprintf(pos,"%f ",cl.snap.ps.origin[0]); //don't start with strcat
sprintf(tmp,"%f ",cl.snap.ps.origin[1]);strcat(pos, tmp);
```
fine.
with
```
sprintf(tmp,"%f ",cl.snap.ps.origin[0]);strcat(pos, tmp);
sprintf(tmp,"%f ",cl.snap.ps.origin[1]);strcat(pos, tmp);
```
not fine.
|
Thestrcat()function expects that the destination argument already contains a properly null-terminated string. In your case, it sounds likeposcontains some junk thatlookslike a null-terminated string, but isn't what you expect.strcat()is dutifully appending on to the end of that junk.
One way to fix this is to initialiseposbefore your code:
```
pos[0] = '\0';
sprintf(tmp,"%f ",cl.snap.ps.origin[0]);strcat(pos, tmp);
sprintf(tmp,"%f ",cl.snap.ps.origin[1]);strcat(pos, tmp);
```
|
The following code segment get an output of 32, I am kind of confusing why?
```
int i=(j=4,k=8,l=16,m=32); printf(“%d”, i);
```
|
Start reading inside the first set of parentheses.
The comma operator evaluates each of several expressions subsequently. It returns the return value of the last expression - in this case, it is 32, because the return value of an assignment is the value assigned.
http://en.wikipedia.org/wiki/Comma_operator
|
I'm using Microsoft Visual Studio 2010. When I add files to my project, they have a.cppextension. To work with C, I have to manually rename the files to.c.
Is there any way to directly add C files, without renaming anything?
|
If I'm understanding correctly, you want to directly add a C file to the project. Unfortunately, I don't think VS provides any means to do so; you'll just have to rename newly added files.
You can rename a file from within the IDE. Right click the file and hit rename (or click on the file and push F2).
Click file, push F2. http://blackninjagames.com/images/rename_file.PNG
|
I want to ask a question about the objective-C or may be theClanguage. I want to ask what is the meaning of the following code of#define? Is it like to declare a variable?
```
#define kMountainNameString @"name"
#define kMountainHeightString @"height"
#define kMountainClimbedDateString @"climbedDate"
```
|
It's a simple text substitution macro. Works the same as in C, C++.
Where kMountainNameString appears the compiler will "paste in"
@"name". Technically speaking this occurs before the compiler by a mechanism called the preprocessor.
|
The text should blink in red color but its not blinking
```
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
void main(void)
{
int driver=DETECT,mode,mx,my,x1,y1,x2,y2;
initgraph(&driver,&mode,"C:\\tc\\bgi");
cleardevice();
mx=getmaxx();
my=getmaxy();
settextstyle(0,HORIZ_DIR,6);
setcolor(RED+BLINK);
outtextxy(mx/2,my/2,"FAHAD");
getch();
closegraph();
}
```
|
That code is targeted at 16-bit MS-DOS, the Win32 DOS-box virtualisation does not support the blinking attribute. I believe that it was supported in 'full-screen' mode, but versions of Windows since XP and 2000 do not support full-screen console or DOS-box presentation.
|
Should functions be madeexternin header files? Or are theyexternby default?
For example, should I write this:
```
// birthdays.h
struct person find_birthday(const char* name);
```
or this:
```
// birthdays.h
extern struct person find_birthday(const char* name);
```
|
FromThe C Book:
If a declaration contains the extern
storage class specifier, or is the
declaration of a function with no
storage class specifier (or both),
then:If there is already a visible declaration of that identifier with
file scope, the resulting linkage is
the same as that of the visible
declaration;otherwise the result is external linkage.
So if this is the only time it's declared in the translation unit, it will have external linkage.
|
Does anyone know of any tool which can convert shell script '.sh' into a C file '.c' ?
|
I doubt that any such tool exists. C and shell files are extremely different languages with completely different purposes, and there is no way to automatically convert one to the other.
|
Let's say I know that some of my C/CPP files include certain headers - is there any reliable information against which libraries I will have to link, other than guessing ?
For example, if I have something like
```
#include "foo.h"
```
and want to find
```
libfoo_abcdef_123.so
```
Is there any 'best practice' how to do that, any place where to look at ?
|
Despite what the other answers here say - no, there isn't. Libraries can (and sometimes do) redefine the same function and the only thing that can attempt to resolve such clashes is the linker, which knows zip about header files.
|
I am trying to compare the parameter of command with argv[] but it's not working. Here is my code.
```
./a.out -d 1
```
In main function
```
int main (int argc, char * const argv[]) {
if (argv[1] == "-d")
// call some function here
}
```
But this is not working... I don't know why this comparison is not working.
|
You can't compare strings using==. Instead, usestrcmp.
```
#include <string.h>
int main (int argc, char * const argv[]) {
if (strcmp(argv[1], "-d") == 0)
// call some function here
}
```
The reason for this is that the value of"..."is a pointer representing the location of the first character in the string, with the rest of the characters after it. When you specify"-d"in your code, it makes a whole new string in memory. Since the location of the new string andargv[1]aren't the same,==will return0.
|
I have libraries which are build using VC++. I want to use the same libraries in a program and build in cygwin gcc compiler. Is this scenario will work?
|
Since C++ doesn't have a standardizedABI, and since Visual C++ and g++ in particular almost certainly have different ABIs, I don't think you can do this. Your only real option is to restrict yourself to C, not C++.
Edit:If all of the libraries that you're using are straight C (extern "C", in C++ terms), then you ought to be able to share libraries between compilers. (Otherwise, your Cygwin and MinGW apps couldn't call the Windows API.) You'll need to be careful to match up calling conventions. For example, the Windows API uses__stdcallinstead of the standard C calling convention. You can tell GCC which calling convention to use withfunction attributes. Google, and your library's header files, should have more information on what calling convention to use.
|
I am interested if there is any difference from the C or C++ compiler perspective whether I use:
```
if (value == a) {
...
}
else if (value == b) {
...
}
else if (value == c) {
...
}
```
versus
```
switch (value) {
case a:
...
break;
case b:
...
break;
case c:
...
break;
}
```
It feels to me that there is no difference, just syntactic. Does anyone know more about it?
Thanks, Boda Cydo.
|
Yes, there are differences. The cascadedifs guarantee evaluation of the conditions in order. The switch guarantees only a single evaluation of whatever's used as the switch parameter. Depending on the compiler, the switch will often take (nearly) constant time regardless of the selected branch, whereas theifcascade pretty much guarantees that the first leg is the fastest, the second second fastest, and so on down to the last being slowest.
|
I would like to for example draw shapes A, B, C then set the blender, then draw shape D and everywhere where shape D is, the scene shows my background color of (1,1,1,0). Thanks
|
I'm not aware of that being possible directly. There are a few possibilities to get the same effect though. The cleanest would probably be to start by filling the stencil buffer with 1's, then drawing shape D into the stencil buffer with 0's, then draw everything else (with the stencil buffer enabled, of course).
|
From my knowledge, *.pc files store metadata about shared libraries. Does the linker automatically use these files when linking against a shared library? If so, where does it search for these files?
|
No, the linker does not utilize.pcfiles. Those files are forpkg-config, which can in turn be used to generate commands to link.
|
I'm making a vector drawing application with OpenGL. Is there a way to implement a clipping mask? Ex: if I have Circle A and Circle B, I only want to see the part of circle B which intersects into Circle A's space. Is there a way to do this that isn't very expensif, I do not want to kill my application. Thanks
|
One possibility would be to draw Circle A into the stencil buffer, then draw Circle B.
|
I have a shared library with soname:libfoo.so
How do I link my binary to libfoo.so such that the shared library name in my binary's ELF section is: libfoo5.so?
I tried creating a symlink: libfoo5.so -> libfoo.so, and then linking my library as such:
g++ ... -o mybinary *.o -Lpath -lfoo5
However, when I print out the dynamic section in my ELF binary, it reads:
readelf -d mybinary
I still get:
Shared library: [libfoo.so]
|
You usually do it when building the shared library. There is a linker option called "soname" that sets it.
I don't know off-hand if you can edit it after the build, but if its possible it is probably included in the package called "elfutils". That package contains several programs designed to manipulate ELF object files.
|
gcc 4.4.4
What am I doing wrong?
```
char x[10];
char y[] = "Hello";
while(y != NULL)
*x++ = *y++;
```
Many thanks for any advice.
|
x++is the short form ofx = x + 1. However,xhere is an array and you cannot modify the address of an array. So is the case with your variableytoo.
Instead of trying to increment arrays, you can declare an integeriand increment that, then access thei'th index of an arrays.
```
char x[10], y[5] = "Hello";
int i = 0;
while (y[i] != 0)
{
x[i] = *y[i];
i++;
}
x[i] = 0;
```
|
I'm using code like the following to check whether a file has been created before continuing, thing is the file is showing up in the file browser much before it is being detected by stat... is there a problem with doing this?
```
//... do something
struct stat buf;
while(stat("myfile.txt", &buf))
sleep(1);
//... do something else
```
alternatively is there a better way to check whether a file exists?
|
Usinginotify, you can arrange for the kernel to notify you when a change to the file system (such as a file creation) takes place. This may well be what your file browser is using to know about the file so quickly.
|
I'm looking for the most efficient method of flipping the sign on all four floats packed in an SSE register.
I have not found an intrinsic for doing this in the Intel Architecture software dev manual. Below are the things I've already tried.
For each case I looped over the code 10 billion times and got the wall-time indicated. I'm trying to at least match 4 seconds it takes my non-SIMD approach, which is using just the unary minus operator.
[48 sec]_mm_sub_ps( _mm_setzero_ps(), vec );
[32 sec]_mm_mul_ps( _mm_set1_ps( -1.0f ), vec );
[9 sec]
```
union NegativeMask {
int intRep;
float fltRep;
} negMask;
negMask.intRep = 0x80000000;
_mm_xor_ps( _mm_set1_ps( negMask.fltRep ), vec );
```
The compiler is gcc 4.2 with -O3. The CPU is an Intel Core 2 Duo.
|
That union is not really needed, best of all worlds (readability, speed and portability):
```
_mm_xor_ps(vec, _mm_set1_ps(-0.f))
```
|
I have a function which expects a 8 bytes long unsigned char.
```
void f1(unsigned char *octets)
{
unsigned char i;
for (i=0;i<8;i++)
printf("(%d)",octets[i]);
}
```
This is how I use it while I have one 64bit integer:
```
unsigned long long ull = 1;
f1((unsigned char *) &ull);
```
(it uses the machine's native endianness.)
My question is, if instead of having 1x64bit integer, I have 2x32bit integers - is there a way to combine them efficiently as an input for this specific function?
```
unsigned long int low = 1;
unsigned long int high = 0;
```
|
Does a union work portably? If so, it's a good approach...
```
union {
struct {
unsigned char CharArray[8];
} ub;
struct {
unsigned long int IntArray[2];
} ul;
unsigned long long ull;
} Foo;
```
|
I'm working on a program which uses shared memory. Multiple instances of said program will either connect to an existing one or create it anew, and give it back to OS when there are no other processes or just detach it and terminate. I thought of using a simple counter to keep track of how many processes use it.
I'm usingatexit()function to do the cleanup, however, afaik, upon receiving SIGKILL signal, processes won't do any cleanup, so if any of those processes don't terminate normally, I might never be able to clean the memory.
Is there a way to specify what to do even after a SIGKILL signal? I'm probably going to write some mechanism similar to a timer to check if processes are still alive, but I'd really like to avoid it if there is another way.
|
No, SIGKILL cannot be caught in any way by your application - if it could, the application could ignore it, which would defeat its purpose.
|
I need to look up MAC address in the local network and I'm using Linux. What I do is send a ARP request with libnet, but after I send 3 requests, the cache still won't update. I use wireshark to catch the packets. From wireshark, I did get 3 ARP replays, after each of my ARP request. Does anyone know how come the ARP cache won't update?
|
The Linux kernel does not accept unsolicited ARP by default. Since the request was sent by your userspace application and not by the kernel, the kernel sees the reply as "unsolicited".
You can change this default in/proc/sys/net/ipv4/conf/*/arp_accept(either on a per-device basis or across all devices).
|
I know this is platform-specific question, however, I would like to do some run-time analysis of an application to detect cache misses and hits. I know cachegrind, a tool for valgrind, and of vtune, and that a slew of other profiling utilities exist. However, I am interested, in implementing my own version of cache-miss detection. I know cachegrind acts as a cache-simulator. Without hacking apart the kernel, how can I detect a cache-miss pragmatically? I have a feeling this is nearly impossible for a user-land application, but I had to ask anyways.
|
There is a way to do this! On Linux you can exploit the Linux Performance Counter Subsystem for this purpose. E.g. have a look here:http://lxr.linux.no/#linux+v2.6.37.3/tools/perf/
|
I want to create a child window that takes up all the space of the left side of main window, but its minimum width is 128 pixels. I also want it to be resizable, but only on the right edge, and makes sure that the width stays at the minimum of 128. Creating the child window with these styles: WS_EX_STATICEDGE, WS_SIZEBOX|WS_CHILD|WS_VISIBLE and handling the WM_NCHITTEST message, I can make it only resizable on the right edge. But I can't make it so the minimum width stays at 128. Can somebody tell me how to do this or if there's another window class that takes care of all this?
|
You must handle the messages which resize the window:WM_POSCHANGING,WM_SIZING,WM_SIZEandWM_POSCHANGED. The most important is to handleWM_SIZINGfor good user experience.
|
Does anyone know if the source code for Objective-C is still available from when it was just a pre-processor? Would be curious to see how it was implemented back then.
Thanks.
|
TheClang LLVM rewriter(rewriter is documented below there) can rewrite Objective-C into C (and is being used by some to compile Objective-C for the Xbox and Windows).
Some discussion here:
http://permalink.gmane.org/gmane.comp.compilers.llvm.devel/32019
|
Are most compilers able to check if an addition operation that was performed earlier in the code resulted in a carry?
For example:
```
unsigned int n = 0xFFFFFFFF; // 8 F's
// doing some stuff here ...
n = n + 1;
// doing some stuff here, without changing the value of @var n
if (n > UINT_MAX) {
// n has a carry
}
```
|
Normally in C the way to tell if overflow occurred (at least with unsigned ints) is if the result of an addition is less than either of the operands. This would indicate an overflow. To the best of my knowledge there is no exception or notification of an overflow.
quick google search:
http://www.fefe.de/intof.html
Unfortunately, there is no way to
access this carry bit from C directly.
|
I defined a matrix structure in C using
```
typedef double mymatrix[30][30][10];
```
so now I define an array of them;
```
mymatrix AA[10];
```
now I tried to access, for a given matrix, the element (i,j,k), so I tried it for AA[5] using
```
AA[5][i][j][k] = 234.0;
```
is this the right way?
Thanks
|
Yes, the first index will be for the final declared variable.
If you:
```
printf("%d\n", &AA[1][0][0][0] - &AA[0][0][0][0]);
```
you should see 9000, or the number of elements inmymatrix.
|
I'm doing a OpenSSL project and I'm completely new to web server. I've got aclient.candserver.c.client.ccreates a connection to the server on port 6008 and reads data fromstdinand then send those data to the server. Theserver.creads data from socket and writes it back out tostdout.
I've got theserver.ccompiled on the server's unix terminal (Solaris 9) but I can't figure out how to run it on Apache 2.2.
PS. I've installed Apache 2.2.15 and OpenSSL 1.0.0a and they are all working.
Any help will be much appreciated!
Z.Zen
|
If the server reads data from a socket, it doesn't need to be run by Apache at all. Just run it from the command line.
You see, Apache is an HTTP server. If a program does its own network communication, it doesn't need an HTTP interface.
|
I am looking for a command-line tool that removes all comments from an input
file and returns the stripped output. It'd be nice it supports popular
programming languages like c, c++, python, php, javascript, html, css, etc. It
has to be syntax-aware as opposed to regexp-based, since the latter will catch
the pattern in source code strings as well. Is there any such tool?
I am fully aware that comments are useful information and often leaving them
as they are is a good idea. It's just that my focus is on different use cases.
|
cloc, a free Perl script, can do this.
Remove Comments from Source CodeHow can you tell if cloc correctly identifies comments? One way to convince yourself cloc is doing the right thing is to use its--strip-commentsoption to remove comments and blank lines from files, then compare the stripped-down files to originals.
It supportsa lotof languages.
|
I'm making an application that draws shapes and I use a camera to draw in other places. Basically, let's say I have a 4x3 rectangle and would like to use glgetpixels to get all the pixels for something that is 1024x768, but my monitor might not support that resolution. How can I render something bigger than the monitor. I do this so I can let the user save a picture of the shapes at an arbitrary resolution. Would using glviewport extend beyond the frame then I can just do glgetpixels?
Thanks
|
You can RTT (render-to-texture) by defining a FBO (Frame Buffer Object) and attaching a texture to it. Check glBindFramebufferEXT().
And after drawing the scene you are able to execute glGetTexImage() and retrieve the pixels for it.
RTT is a very well established and documented technique.
|
I am using a variable-sized C struct, as follows:
```
typedef struct {
int num_elems;
int elem1;
} mystruct;
// say I have 5 elements I would like to hold.
mystruct * ms = malloc(sizeof(mystruct) + (5-1) * sizeof(int));
ms->num_elems = 5;
// ... assign 5 elems and use struct
free(ms);
```
Will this last free() free everything that was malloc'd, or only sizeof(mystruct)?
|
Yes. This will free the whole block that was allocated usingmalloc.
If you allocate a single block of memory usingmalloc(like you do in your example), then you need to callfreeexactly once to free that entire block.
|
I once seen a -wired- operator in C++ which assigns value if greater than..it was a combination of?,<and=
e.g. let x = value if value is greater than x
Ido not meanx=(x<value)x:value
It was some sort ofx<?=value
But I can not remember it exactly, and can not find it online... Can some one remind me of it?
Thanks,
|
There is no operator that assigns variables based on their relative values.
However, there is the ?: operator:
```
x = value > x ? value : x;
```
If you read it out loud from left to right, it makes sense.
|
I am working on a small C application and I am capturing a value from the command line. I would like to capture the value and use it to initialize an array. Here is what I'm trying to do.
```
int main(int argc, char* argv[]) {
int option = atoi(argv[2]);
int values[option];
......
}
```
I am getting a compilation because my option variable is not a const.
Error: Error 2 error C2057: expected constant expression
Is there a way I can do this?
Thanks for your help!
|
If the size is not known at compile-time, you need to allocate the memory dynamically, withmalloc:
```
int main(int argc, char* argv[]) {
int option = atoi(argv[2]);
int* values = malloc(option * sizeof(int));
/* ...... */
free(values); /* Deallocate the memory when you are done with it */
}
```
|
I need to write a repeating pattern to memory (e.g.0x11223344), so that the whole memory looks like (in hex):
```
1122334411223344112233441122334411223344112233441122334411223344...
```
I can't figure out how to do it withmemset()because it takes only a single byte, not 4 bytes.
Any ideas?
|
On OS X, one usesmemset_pattern4( )for this; I would expect other platforms to have similar APIs.
I don't know of a simple portable solution, other than just filling in the buffer with a loop (which is pretty darn simple).
|
```
char *p = " woohoo";
int condition = /* some calculation applied to p */
/* to look for all 0x20/blanks/spaces only */
if (condition)
{
}
else
{
printf("not ");
}
printf("all spaces\n");
```
|
One-liner:
```
int condition = strspn(p, " ") == strlen(p);
```
Slightly more optimized:
```
int condition = p[strspn(p, " ")] == '\0';
```
|
What is the best way to analyze crashes on Linux?
We expect to build the software and deliver a release version to testers. The testers may not be able remember how to reproduce the crash or the crash may be totally intermittent. They also will not have a development environment on their machines. The software is written in C/C++ and compiled into native machine code for distribution.
|
If you have space on the disk, let the application create its coredump when it crashes.
```
ulimit -c unlimited
```
Later you can debug it with GDB.
|
I am writing a program that downloads tar.xz files from a server and extracts them in a certain place. I am struggling to find a away of extracting the tar.xz file in the certain place. I am using Qt so a more Qt-way of doing it would be useful, but I don't really mind.
|
There is no support for archives in Qt. You can either have a look at the KDE library which offers support for virtual file systems or you can useQProcessto calltardirectly. Use-C <dir>(uppercase C) to specify the directory to extract to.
[EDIT] There also islibtar(BSD license).
|
```
char *test = "hello";
test = change_test("world");
printf("%s",test);
char* change_test(char *n){
printf("change: %s",n);
return n;
}
```
im trying to pass a 'string' back to a char pointer using a function but get the following error:
assignment makes pointer from integer without a cast
what am i doing wrong?
|
A function used without forward declaration will be considered having signatureint (...). You should either forward-declare it:
```
char* change_test(char*);
...
char* test = "hello";
// etc.
```
or just move the definitionchange_testbeforewhere you call it.
|
When reading the /proc/$PID/maps you get the mapped memory regions.
Is ther a way to dump one of this regions?
```
$ cat /proc/18448/maps
...[snip]...
0059e000-005b1000 r-xp 00000000 08:11 40 /usr/local/lib/libgstlightning.so.0.0.0
005b1000-005b2000 r--p 00012000 08:11 40 /usr/local/lib/libgstlightning.so.0.0.0
005b2000-005b3000 rw-p 00013000 08:11 40 /usr/local/lib/libgstlightning.so.0.0.0
...[snip]...
```
Thanks
|
Nah! Callptrace()withPTRACE ATTACH. Then open/proc/<pid>/mem, seek to the region offset, and read the length of the region as given in/proc</pid>/maps.
Here's aprogram I wrotethat does it in C. Here's amodule I wrotethat does it in Python (and the ptrace binding). For the finish, aprogram that dumps all regions of a process to files.
Enjoy!
|
C99 still isn't supported by many compilers, and much of the focus is now on C++, and its upcoming standard C++1x.
I'm curious as to what C will "get" in its next standard, when it will get it, and how it will keep C competitive. C and C++ are known to feed on one another's improvements, will C be feeding on the C++1x standard?
What can I look forward to in C's future?
|
TheISO/IEC 9899:2011 standard, aka C11, was published inDecember 2011.
The latest draft isN1570; I'm not aware of any differences between it and the final standard. There's already a Technical Corrigendum fixing an oversight in the specification of__STDC_VERSION__(now201112L) and the optional__STDC_LIB_EXT1__(now201112L).
|
Is this
```
if( (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
(wcscmp(FileData.cFileName, L".") != 0) &&
(wcscmp(FileData.cFileName, L"..") != 0) )
```
the same as this:
```
if( (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
wcscmp(FileData.cFileName, L".") &&
wcscmp(FileData.cFileName, L"..") )
```
And also if you usestrcmpinstead ofwcscmp? It should check equality (strict) of the name with ".." and "." (directory search).
Thanks!
|
If I'm not mistaken, both examples do the same thing.
|
This question already has answers here:Is there a 128 bit integer in gcc?(3 answers)Closed4 years ago.
Does gcc support 128-bit int on amd64?
How to define it?
How to use scanf/printf to read/write it?
|
GCCsupports built-in__int128andunsigned __int128types (on 64-bit platforms only), but it looks like formatting support for 128-bit integers is less common in libc.
Note:<stdint.h>defines__int128_tand__uint128_ton versions before gcc4.6. See alsoIs there a 128 bit integer in gcc?for a table of gcc/clang/ICC versions.
How to know if __uint128_t is definedfor detecting__int128
|
I have a C++ program (.cpp) inside which I wish to use some of the functions which are present inside the C header files such as stdio.h, conio.h, stdlib.h, graphics.h, devices.h etc.
I could include the stdio.h library inside my cpp file as :#include <cstdio>.
How do I include the other library files?
How do I add the graphics.h library?
I'm using Microsoft Visual Studio 6.0 Enterprise Edition and also Turbo C++ 3.0.
|
For a list of C standard C headers (stdio, stdlib, assert, ...), prepend a c and remove the .h.
For example stdio.h becomes cstdio.
For other headers, use
```
extern "C"
{
#include "other_header.h"
}
```
|
My application redraws the screen every time the mouse moves. I have not at all handled WM_KEYDOWN and I noticed that when I press shift or ctrl, it does not redraw on mouse mouse, nor does it seem to really do anything else. What could cause such a thing? If I press any other key like Z or X it does exactly what it should.
Thanks
|
No, they certainly don't prevent events from happening. But they seem to be preventing your code from recognizing them.
There's a handful of flags included with the event code, and they represent pressed keys/buttons. You'll probably notice the same effect withAltor a pressed mouse button. My guess would be that you're comparing a combination of event code and keyboard status with a combination of event code and 0, and that comparison is failing when those shift keys are pushed.
|
```
test.c(6) : warning C4013: 'add' undefined; assuming extern returning int
```
I've encountered many times when anundefinedfunction will report anerror,thus stopping the building process.
Why this time just a warning?
|
Perhaps you normally code in C++, and this is a C program. C++ is stricter than C; it won't let you call undeclared functions.
|
Or do I need to instruct the compiler explicitly ?
|
With a user name like "ieplugin" the answer would probably be No. COM servers don't have .lib files. For regular DLLs, the .lib file is produced by the linker, not the compiler. The /IMPLIB option generates them.
|
I'm building a program that has several functions that need to read data from a file. Since the functions are used fairly frequently, opening and closing the file for each call would be too time consuming, so my plan was to make the FILE* object global, and have the file open the whole duration of the program. Apparently, though, it's not possible, since this:
```
#include <fstream>
FILE * yhtit;
yhtit = fopen("thefile.txt","r");
int main() {
return 0; }
```
gives error:main.cpp|54|error: expected constructor, destructor, or type conversion before ‘=’ token|
What's the best way to keep a file open the whole duration of the program, without having to separately pass the FILE* object to every function that needs it?
|
You almost got it right. Try this:
```
#include <fstream>
FILE * yhtit;
int main() {
yhtit = fopen("thefile.txt","r");
//Do your thing here.
fclose(yhtit);
return 0;
}
```
|
What is C# analog of C snprintf()?
InC code here we use
```
snprintf(buf, sizeof(buf), outfilename, frame);
```
What could be its exact analog?
|
StringBuilder.AppendFormatString.Formatis the closest. It performs the same operation, but do note that the format strings arein a different format.
UsingString.Format:
```
string buf = string.Format("{0}", frame);
```
UsingStringBuilder.AppendFormat:
```
StringBuilder builder = new StringBuilder();
builder.AppendFormat("{0}", frame);
```
|
How toturn .h file +dll into some kind of .Net wrapper? or something like that? (no C\C++ sources just h files)
|
If you have the header file, and use many implement from that dll you can use swig(http://www.swig.org/) to generate wrapper automatically. Then compile as a dll and invoke the interfaces or class from .Net code.
Or if you only use few method from the dll, just use P/Invoke.
|
I want to send integers to Arduino via a serial connection.
For example, when I send "1" the data received by Arduino is "49"
and when I send "a" the data received by Arduino is "97"
There are two functions inPython,ord()andunichr(). They behaved like this:
```
unichr(97) = u"a"
ord(u"a")=97
```
Are there equivalent C functions?
|
Usethe alphanumeric to integer function.
You may also findheader cstdlib, stdlib.h, C Standard General Utilities Libraryuseful. Although it says C++, this particular section is the standard C library. Notice that you can use C++ with Arduino.
|
I am just unable to get the hang of dp. I know what I've to do but am just unable to implement it.E.g this practice problem from 'Codechef'
http://www.codechef.com/problems/MIXTURES/
If i consider the min smoke for mixtures i to j as m[i,j]
then
```
for k<- i to j
m[i,j]=min(m[i,k]+m[k+1,j]+cost of mixing the resulting mixtures)
```
Is this correct?
and how do I keep updating the colors of the mixtures for diff k and then revert back to original for the next k?
|
Yes, you are on the right track.
The color of m[i,j] does not depend on the order of the mixtures.
|
Suppose in C I have the functions
```
type* func (type*);
const type* func_const (const type*);
```
such that they both have the exact same internal logic.
Is there a way I can merge the two into one function, where if given a const type, it returns a const type; and if given a non-const type, it returns a non-const type? If not, what is a good way of dealing with this? Define one in terms of the other via explicit casting perhaps?
|
You can't automate it, but you can certainly have the logic in a single location:
```
const type* func_const (const type*)
{
/* actual implementation goes here */
}
type* func (type* param)
{
/* just call the const function where the "meat" is */
return (type*)func_const(param);
}
```
|
I have the following c code:
```
void handler(int n) {
printf("n value: %i\n");
}
int main() {
signal(SIGTSTP, handler); // ^Z at keyboard
for(int n = 0; ; n++) {
}
}
```
I am curious what the n parameter is in the handler function. When you press^Zit usually prints either:8320,-1877932264or-1073743664. What are these numbers?
Edit:Ops I wrote my printf wrong. I corrected it to be:
```
void handler(int n) {
printf("n value: %i\n",n);
}
```
Now the value of n is always: 18. What is this 18?
|
You haven't passed any number to printf(). Should be:
```
void handler(int n) {
printf("n value: %i \n", n);
}
```
Thenwill be the signum you are catching, in your case 20. Seeman 2 signalfor a description. Also note that the manpage recommends usingsigaction()instead ofsignal.
|
This question already has answers here:Closed13 years ago.
Possible Duplicate:Why do people use __(double underscore) so much in C++
I was studying the Linux kernel programming code.
There are some data structures and functions which start with a double underscore like:
```
__u32 len
```
How is that different from normal variables?
|
It means it's a system-reserved name. The C standard says that all names beginning with two underscore, or underscore and capital letter, are reserved for the use of the system or compiler and should not be defined in application code.
|
Inlimits.h, and in various places in the POSIX manpages, there are references toPATH_MAXandNAME_MAX.
How do these relate to one another?
Where is the official documentation for them?
How can I obtain them at run time, and (where relevant) compile time for the C, Python, and GNU (shell) environments?
|
PATH_MAXis the maximum length of a filesystem path.NAME_MAXis the maximum length of a filename (in a particular spot). So,/foo/baris restricted byPATH_MAX, and only thebarportion has its length limited byNAME_MAX.
You can get these at run time viapathconf, as_PC_PATH_MAXand_PC_NAME_MAX, although standard practice is generally just to use the static macros at compile time. I suppose it would be better to use the run-time option because you could potentially support longer values that way, but I'm not sure what (if any) systems actually provide a return frompathconfwhich is greater than the value of thePOSIX_FOO_MAXvalues.
|
If I have two char arrays like so:
```
char one[200];
char two[200];
```
And I then want to make a third which concatenates these how could I do it?
I have tried:
```
char three[400];
strcpy(three, one);
strcat(three, two);
```
But this doesn't seem to work. It does ifoneandtwoare setup like this:
```
char *one = "data";
char *two = "more data";
```
Anyone got any idea how to fix this?
Thanks
|
If 'one' and 'two' does not contain a '\0' terminated string, then you can use this:
```
memcpy(tree, one, 200);
memcpy(&tree[200], two, 200);
```
This will copy all chars from both one and two disregarding string terminating char '\0'
|
I have com across an article which states that.COMfiles are better for small application than.EXEfiles. What are.COMfiles? How do we create a.COMfile? How are they better than.EXEfiles? I also want to know whether.COMfiles are still widely used?
Any Suggestions.
|
Did this article come from 1985?COM filesare long dead, as they are DOS only, may only be 64 KiB big and have many other issues.
They used to be a much simpler format then EXE, as you could create a valid com executable with a few lines indebug.exeor an assembler. I am getting a little bit nostalgic here...
|
I have referred quite a few books on C, C++, etc. in fact i have even read the Dragon book on Compilers.
But my basic doubt remains,
is there any link or book i can read which explains a simple C program creating from writing source code in a Editor to Compilation to Linking?
Would appreciate an internet link is provided.
|
As example this is for *nix OS:http://www.thegeekstuff.com/2009/09/how-to-write-compile-and-execute-c-program-on-unix-os-with-hello-world-example/. (there are source code edited by text editor, not by IDE)I found this link using google with "C hello world howto" request. You can try similar requests If you need Windows (or other OS) specific manual
|
I'm here looking at some C source code and I've found this:
```
fprintf(stderr, _("Try `%s --help' for more information.\n"), command);
```
I already saw the underscore when I had a look at wxWidget, and I read it's used for internationalization. I found it really horrible (the least intutive name ever), but I tought it's just another weird wxWidget convention.
Now I find it again in some Alsa source. Does anyone know where it comes from?
|
It comes from GNUgettext, a package designed to ease the internationalization process. The_()function is simply a string wrapper. This function basically replaces the given string on runtime with a translation in the system's language, if available (i.e. if they shipped a.mofile for this language with the program).
|
I have the following code, for an embedded platform where an int is 16 bits and a long int is 32 bits:
```
#define MULTIPLIER 0x1000
static void my_function(uint16_t i, void *p)
{
uint32_t start = MULTIPLIER * i;
...
}
```
My compiler gives me the warning:
```
Warning 1 : lower precision in wider context: '*'
```
for this line.
What does this really mean? I can make the warning go away by changing the #define to
```
#define MULTIPLER 0x1000ul
```
(explicitly making it an unsigned long) but I would like to understand the warning.
|
It's warning you that the multiplication will take place using 16-bit values, and the 16-bit result will then be converted to a 32-bit result. This might not be what you expect (the 16-bit multiplication might overflow), hence the warning.
This forum postingcovers the issue
|
I need something to embed in my C/C++ program to interpret formulas of the like x*log(x) or sin(x). I would like something small and simple, otherwise I can just embed Python, or Ch, or Scheme, or you name it. But all I need is simple formulas. I have searched the web without luck. Although I don't require it, performance (e.g., the use of a simple JIT) would be a bonus.
|
Use Reverse Polish notation. There are few algorithms:1. Parse equation and convert to infix notation (that is easy, you simply identify chain of symbols)2. Using Dijkstra's shunting-yard algorithm convert infix to RPN.3. Using DFS calculate the expression
I'm sure there is a lot implementations on the net. I even wrote my own few years ago (without functions feature).
|
How is the following line interpreted by GCC compiler:
```
printf("HELLO");
```
I want to know this because when I am running following program:
```
main()
{
printf(5+"Good Morning");
}
```
The program is printing:
```
Morning
```
Why is the compiler is starting the printing from the sixth character?
|
This is an artifact of C pointer-arithmetic;printfis just a red herring.
The type of a string literal (such as"Good morning") isconst char *. Your code is equivalent to:
```
const char *p = "Good morning";
p = p + 5;
printf(p);
```
Adding a pointer and an integer produces a pointer to the 5th element in the sequence.
|
Can FFmpeg encode video in VP8 codec? (I mean its trunk vercion)
|
Straight from the home page atffmpeg.org: the latest version (0.6) lists VP8 as supported via Google's libvpx library, for both encoding and decoding
|
Can anyone summarize what is the correct usage ofrealloc()?
What do you do whenrealloc()fails?
From what I have seen so far, it seems that ifrealloc()fails, you have tofree()old pointer. Is that true?
Here is an example:
```
1. char *ptr = malloc(sizeof(*ptr) * 50);
2. ...
3. char *new_ptr = realloc(ptr, sizeof(*new_ptr) * 60);
4. if (!new_ptr) {
5. free(ptr);
6. return NULL;
7. }
```
Supposerealloc()fails on line3. Am I doing the right thing on line5byfree()ingptr?
|
Fromhttp://www.c-faq.com/malloc/realloc.html
If realloc cannot find enough space at all, it returns a null pointer, and leaves the previous region allocated.
Therefore you would indeed need to free the previously allocated memory still.
|
I am facing a problem where the C library exposes only an interface that writes the data to a CFILEstructure. This means all the data get saved to disk. I want this library to save the data to memory instead.
Is there a way to emulateFILEstructure in my code and make it save the data in memory instead? I imagineFILEhas various pointers to functions and I could write my own functions and make them allocate memory and onfwritewrite the data to memory.
Can this be done?
Thanks, Boda Cydo.
|
A portable solution would be to usefmemopenoropen_memstreamif these functions are available (they've been part of GNU libc for a long time and they were added to POSIX in 2008) and simply write to a temporary file then read back into memory if they're not.
|
Is this
```
if( (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
(wcscmp(FileData.cFileName, L".") != 0) &&
(wcscmp(FileData.cFileName, L"..") != 0) )
```
the same as this:
```
if( (FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
wcscmp(FileData.cFileName, L".") &&
wcscmp(FileData.cFileName, L"..") )
```
And also if you usestrcmpinstead ofwcscmp? It should check equality (strict) of the name with ".." and "." (directory search).
Thanks!
|
If I'm not mistaken, both examples do the same thing.
|
This question already has answers here:Is there a 128 bit integer in gcc?(3 answers)Closed4 years ago.
Does gcc support 128-bit int on amd64?
How to define it?
How to use scanf/printf to read/write it?
|
GCCsupports built-in__int128andunsigned __int128types (on 64-bit platforms only), but it looks like formatting support for 128-bit integers is less common in libc.
Note:<stdint.h>defines__int128_tand__uint128_ton versions before gcc4.6. See alsoIs there a 128 bit integer in gcc?for a table of gcc/clang/ICC versions.
How to know if __uint128_t is definedfor detecting__int128
|
I have a C++ program (.cpp) inside which I wish to use some of the functions which are present inside the C header files such as stdio.h, conio.h, stdlib.h, graphics.h, devices.h etc.
I could include the stdio.h library inside my cpp file as :#include <cstdio>.
How do I include the other library files?
How do I add the graphics.h library?
I'm using Microsoft Visual Studio 6.0 Enterprise Edition and also Turbo C++ 3.0.
|
For a list of C standard C headers (stdio, stdlib, assert, ...), prepend a c and remove the .h.
For example stdio.h becomes cstdio.
For other headers, use
```
extern "C"
{
#include "other_header.h"
}
```
|
My application redraws the screen every time the mouse moves. I have not at all handled WM_KEYDOWN and I noticed that when I press shift or ctrl, it does not redraw on mouse mouse, nor does it seem to really do anything else. What could cause such a thing? If I press any other key like Z or X it does exactly what it should.
Thanks
|
No, they certainly don't prevent events from happening. But they seem to be preventing your code from recognizing them.
There's a handful of flags included with the event code, and they represent pressed keys/buttons. You'll probably notice the same effect withAltor a pressed mouse button. My guess would be that you're comparing a combination of event code and keyboard status with a combination of event code and 0, and that comparison is failing when those shift keys are pushed.
|
```
test.c(6) : warning C4013: 'add' undefined; assuming extern returning int
```
I've encountered many times when anundefinedfunction will report anerror,thus stopping the building process.
Why this time just a warning?
|
Perhaps you normally code in C++, and this is a C program. C++ is stricter than C; it won't let you call undeclared functions.
|
Or do I need to instruct the compiler explicitly ?
|
With a user name like "ieplugin" the answer would probably be No. COM servers don't have .lib files. For regular DLLs, the .lib file is produced by the linker, not the compiler. The /IMPLIB option generates them.
|
I'm building a program that has several functions that need to read data from a file. Since the functions are used fairly frequently, opening and closing the file for each call would be too time consuming, so my plan was to make the FILE* object global, and have the file open the whole duration of the program. Apparently, though, it's not possible, since this:
```
#include <fstream>
FILE * yhtit;
yhtit = fopen("thefile.txt","r");
int main() {
return 0; }
```
gives error:main.cpp|54|error: expected constructor, destructor, or type conversion before ‘=’ token|
What's the best way to keep a file open the whole duration of the program, without having to separately pass the FILE* object to every function that needs it?
|
You almost got it right. Try this:
```
#include <fstream>
FILE * yhtit;
int main() {
yhtit = fopen("thefile.txt","r");
//Do your thing here.
fclose(yhtit);
return 0;
}
```
|
I was going through this linkWill it optimizeand wondered how can we know what optimizations are done by a particular compiler.
Like does VC8.0 convert if-else statements to switch-case?
Is such information available on msdn?
|
As everyone seems to be bent on telling the OP that he shouldn't worry about it, there is some useful although not as specific as the OP requested) information about compiler optimization (options).
You'll have to figure out what flags you're using, especially for MSVC and Intel (GCC release build should default to -O2), but here are the links:
GCCMSVCIntel
This is about as close as you'll get before disassembling your binary after compilation.
|
My program (a text-mode web browser) is dynamically allocating memory.
I do free unneeded blocks during runtime, of course. And I do free everything before normal termination - so that memory leak checkers won't give me false positives (and to be flexible should major refactorings ever become needed).
Now, what I donotdo is freeing memory before abnormal termination. (Currently, my program terminates on signals and after failed mallocs/reallocs.)
My question is: Do you consider this bad style? Should I free on abnormal termination?
|
No. I think it's perfectly acceptable to simply throw up your hands and let the OS reclaim the memory after the program terminates. I think if this is truly an abnormal situation and the intention is to have the program terminate, then a well-behaved program should simply clean up any disk resources/locks, and exit as quickly as possible.
|
```
pthread_rwlock t1;
pthread_rwlock_wrlock(&t1);
pthread_rwlock t2 = t1;
```
what happend?
is t2 locked or not?
|
Nothing special happens.pthread_rwlock_t(notpthread_rwlock, AFAIK) is an opaque C struct. Copying the variable simply copies the struct, byte for byte.
At the Pthreads level, copying apthread_rwlock_tresults in undefined behaviour. Don't do it.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.