I am trying to understand the inner workings of errno, and tried the following example file from cppreference, but got errors during compiling:
$ gcc errno_ex.c
errno_ex.c: In function 'main':
errno_ex.c:33:10: error: 'math_errhandling' undeclared (first use in this function)
puts(math_errhandling & MATH_ERRNO ? "set" : "not set");
^~~~~~~~~~~~~~~~
errno_ex.c:33:10: note: each undeclared identifier is reported only once for each function it appears in
errno_ex.c:33:29: error: 'MATH_ERRNO' undeclared (first use in this function)
puts(math_errhandling & MATH_ERRNO ? "set" : "not set");
^~~~~~~~~~
The (untouched) example code is:
#include <stdio.h>
#include <math.h>
#include <errno.h>
void show_errno(void)
{
const char *err_info = "unknown error";
switch (errno) {
case EDOM:
err_info = "domain error";
break;
case EILSEQ:
err_info = "illegal sequence";
break;
case ERANGE:
err_info = "pole or range error";
break;
case 0:
err_info = "no error";
}
fputs(err_info, stdout);
puts(" occurred");
}
int main(void)
{
fputs("MATH_ERRNO is ", stdout);
puts(math_errhandling & MATH_ERRNO ? "set" : "not set");
errno = 0;
1.0/0.0;
show_errno();
errno = 0;
acos(+1.1);
show_errno();
errno = 0;
log(0.0);
show_errno();
errno = 0;
sin(0.0);
show_errno();
}
I am not sure what is happening. These errors happen when I compile in VS code in Windows ( C complier set to C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.29.30037/bin/Hostx86/x86/cl.exe by default, and using C17 standard).
When I try to duplicate this on my Macbook VS code, it compiled without error. So I am not sure where is the problem: is my compiler too old to recognize these macros?
Edit:
I think the macro definition of math_errhandling is platform-specific, thus not quite portable across different OS platforms. errno macro still works in my Windows-based VS Code IDE, which I am happy with. It is just that the math_errhandling thing is a bit non-portable and mysterious.
Related
So I'm a noob when it comes to this sort of stuff.
I'm struggling to compile a climate model on macOS and I've boiled it down to what is going on here:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sched.h>
#include <errno.h>
#include <sys/resource.h>
#include <sys/syscall.h>
static pid_t gettid(void)
{
return syscall(__NR_gettid);
}
/*
* Returns this thread's CPU affinity, if bound to a single core,
* or else -1.
*/
int get_cpu_affinity(void)
{
cpu_set_t coremask; /* core affinity mask */
CPU_ZERO(&coremask);
if (sched_getaffinity(gettid(),sizeof(cpu_set_t),&coremask) != 0) {
fprintf(stderr,"Unable to get thread %d affinity.
%s\n",gettid(),strerror(errno));
}
int cpu;
int first_cpu = -1; /* first CPU in range */
int last_cpu = -1; /* last CPU in range */
for (cpu=0;cpu < CPU_SETSIZE;cpu++) {
if (CPU_ISSET(cpu,&coremask)) {
if (first_cpu == -1) {
first_cpu = cpu;
} else {
last_cpu = cpu;
}
}
}
return (last_cpu == -1) ? first_cpu : -1;
}
int get_cpu_affinity_(void) { return get_cpu_affinity(); } /* Fortran interface */
/*
* Set CPU affinity to one core.
*/
void set_cpu_affinity( int cpu )
{
cpu_set_t coremask; /* core affinity mask */
CPU_ZERO(&coremask);
CPU_SET(cpu,&coremask);
if (sched_setaffinity(gettid(),sizeof(cpu_set_t),&coremask) != 0) {
fprintf(stderr,"Unable to set thread %d affinity. %s\n",gettid(),strerror(errno));
}
}
void set_cpu_affinity_(int *cpu) { set_cpu_affinity(*cpu); } /* Fortran interface */
When compiling I get a couple of errors:
First - identifier "cpu_set_t" is undefined, Second - identifier "CPU_SETSIZE" is undefined
I've done my googling and it seems to me that sched_getaffinitiy(), cpu_set_t and perhaps some other things are not present in macOS.
With all kinds of C programming I'm really out of my depth. I was wondering if anyone here knows of an alternative way of doing this for macOS and how I could go about doing that.
I've attached the full error report below.
Kind Regards,
Neil :)
Complete error report:
(python2) salvare:MASTERS Neil$ python run.py
Working directory for exp 'playground' already exists
RRTM compilation disabled. Namelist set to gray radiation.
Writing path_names to '/Users/Neil/MASTERS/ISCA_TEMP/playground/path_names'
Running compiler
/Users/Neil/MASTERS/ISCA_TEMP/playground/compile.sh: line 21: module: command not found
loadmodules
/Users/Neil/MASTERS/Isca/src/extra/loadmodule: line 3: module: command not found
/Users/Neil/MASTERS/Isca/src/extra/loadmodule: line 4: module: command not found
/Users/Neil/MASTERS/Isca/src/extra/loadmodule: line 5: module: command not found
/Users/Neil/MASTERS/Isca/src/extra/loadmodule: line 6: module: command not found
/Users/Neil/MASTERS/ISCA_TEMP/playground/compile.sh: line 23: module: command not found
/Users/Neil/MASTERS/ISCA_TEMP/playground/compile.sh: line 24: ulimit: stack size: cannot modify limit: Operation not permitted
./compile_mppn.sh: line 13: module: command not found
./compile_mppn.sh: line 14: module: command not found
./compile_mppn.sh: line 15: module: command not found
- mppnccombine.c:162:24: warning: format string is not a string literal (potentially insecure) [-Wformat-security]
sprintf(outfilename,argv[outputarg]); outlen=strlen(outfilename);
^~~~~~~~~~~~~~~
/usr/include/secure/_stdio.h:47:56: note: expanded from macro 'sprintf'
__builtin___sprintf_chk (str, 0, __darwin_obsz(str), __VA_ARGS__)
^~~~~~~~~~~
mppnccombine.c:162:24: note: treat the string as an argument to avoid this
sprintf(outfilename,argv[outputarg]); outlen=strlen(outfilename);
^
"%s",
/usr/include/secure/_stdio.h:47:56: note: expanded from macro 'sprintf'
__builtin___sprintf_chk (str, 0, __darwin_obsz(str), __VA_ARGS__)
^
1 warning generated.
ln: /Users/Neil/MASTERS/ISCA_TEMP/playground/exec/mppnccombine.x: File exists
Makefile is ready.
mpicc -Duse_libMPI -Duse_netCDF -Duse_LARGEFILE -DINTERNAL_FILE_NML -DOVERLOAD_C8 -DRRTM_NO_COMPILE -I/usr/local/include -D__IFC -c /Users/Neil/MASTERS/Isca/src/shared/mpp/affinity.c
......................................................................................................................../Users/Neil/MASTERS/Isca/src/shared/mpp/affinity.c(35): error: identifier "__NR_gettid" is undefined
eturn syscall(__NR_gettid);
^
/Users/Neil/MASTERS/Isca/src/shared/mpp/affinity.c(44): error: identifier "cpu_set_t" is undefined
cpu_set_t coremask; /* core affinity mask */
^
/Users/Neil/MASTERS/Isca/src/shared/mpp/affinity.c(47): error: identifier "cpu_set_t" is undefined
if (sched_getaffinity(gettid(),sizeof(cpu_set_t),&coremask) != 0) {
^
/Users/Neil/MASTERS/Isca/src/shared/mpp/affinity.c(54): error: identifier "CPU_SETSIZE" is undefined
for (cpu=0;cpu < CPU_SETSIZE;cpu++) {
^
/Users/Neil/MASTERS/Isca/src/shared/mpp/affinity.c(75): error: identifier "cpu_set_t" is undefined
cpu_set_t coremask; /* core affinity mask */
^
/Users/Neil/MASTERS/Isca/src/shared/mpp/affinity.c(79): error: identifier "cpu_set_t" is undefined
if (sched_setaffinity(gettid(),sizeof(cpu_set_t),&coremask) != 0) {
^
compilation aborted for /Users/Neil/MASTERS/Isca/src/shared/mpp/affinity.c (code 2)
make: *** [affinity.o] Error 2
ERROR: mkmf failed for fms_moist
CRITICAL - Compilation failed.
Traceback (most recent call last):
File "run.py", line 25, in <module>
exp.compile()
File "/Users/Neil/MASTERS/Isca/src/extra/python/gfdl/experiment.py", line 298, in compile
raise e
sh.ErrorReturnCode_1:
RAN: /bin/bash /Users/Neil/MASTERS/ISCA_TEMP/playground/compile.sh
STDOUT:
STDERR:
Your googling put you on the right track - sched_getaffinity() and the cpu_set_t structure that it uses are linux-specific, and are not available on all platforms. Mac OSX in particular seems to be missing them.
However, there are alternatives. I found a blog post from someone porting code to OSX who found an alternative using sysctlbyname(). The code on that site reimplements sched_getaffinity() on Mac OSX by requesting the machdep.cpu.core_count, and using that to build their own version of cpu_set_t.
#include <avr/io.h>
int main(void)
{
DDRB=0b11111111; //PORTB as output port connected to motors;
DDRC=0b0000000; //PORTC Input port connected to sensors;
int left_sensor=0;
int right_sensor=0;
while(1)
{
left_sensor=PINC&0b00000001;
right_sensor=PINC&0b00001000 ;
if((left_sensor==0b0000000)&&(right_sensor==0b0000000))
{
PORTB=0b00000000;
}
else if((left_sensor==0b00000001)&&(right_sensor==0b00001000))
{
PORTB=0b00010010;
}
else if((left_sensor==0b0000000)&&(right_sensor==0b0001000))
{
PORTB=0b00000010;
}
else if((left_sensor==0b00000001)&&(right_sensor==0b0000000))
{
PORTB=0b00010000;
}
}
}
Its showing "expected expression before while".
I have tried everything but i am not getting any solution to it.
Error:Expected Expression before 'while'
Compiler:Atmel Studio 7
If I copy & pasted the code from your question remove the AVR specific lines and attempt to compile it I get the following:
source_file.c: In function ‘main’:
source_file.c:4:10: error: stray ‘\315’ in program
int right_sensor=0;
^
source_file.c:4:10: error: stray ‘\276’ in program
source_file.c:5:10: error: expected ‘,’ or ‘;’ before ‘while’
while(1)
^
Deleting the line with the declaration of right_sensor and rewriting it solves the problem - you appear to have some strange non-printing characters in the line.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main(void)
{
int a,b,sub,i,count=0;char buffer[20],w[20];
scanf("%d",&a);
scanf("%d",&b);
sub=a-b;
if(sub>0)
{
scanf("%s",w); /*wrong answer*/
itoa(sub,buffer,10);
int l=strlen(buffer);
for(i=0;i<l;i++)
{
if(w[i]==buffer[i])
count++;
}
((count==l || count==l-1) && w[0]!='0') ? printf("accepted") : printf("Not accepted");
}
else printf("Sub operation returned negative value");
}
The output of the compiler is
prog.c:4:6: warning: return type of 'main' is not 'int' [-Wmain]
void main(void)
^
prog.c: In function 'main':
prog.c:13:1: warning: implicit declaration of function 'itoa' [-Wimplicit-function-declaration]
itoa(sub,buffer,10);
^
/home/HCDVgj/ccHBnrc7.o: In function `main':
prog.c:(.text.startup+0x61): undefined reference to `itoa'
collect2: error: ld returned 1 exit status
I did not use any long int variables but i still get ld return 1 exists. how to debug these errors
int main() This is teh first thing you should do.
scanf("%19s",w); This is better.
itoa is non standard (so you will not find it in any standard implementaion) better use snprintf()
printf('%s",((count==l || count==l-1) && w[0]!='0') ? "accepted" : "Not accepted"); More compact I would say.
Use of snprintf
snprintf(target, size_of_target1, "%d", source2);
sprintf takes no parameter specifying the number of bytes to write which may lead to buffer overflow which is not a good thing.
1 : In bytes
2 : source is in integer here
Few things worth mentioning to clear your idea or to be more precise
The output you specified is not output of the c program ... in the process of compilation your compiler run into error and then it generates those output. -CiaPan
main() shouldn't be of void return type it is expected to return 0 in case of normal termination. Abnormal termination is usually signaled by a non-zero.-David C. Rankin
I don't know why you're talking about "long int variables".
The first warning can be fixed by changing void main(void) to int main(void) and adding a return 0; at the end.
The second warning tells you that the compiler doesn't know what itoa is.
The following linker error tells you that the linker (ld) also doesn't know what itoa is, and that's why compilation fails.
The reason itoa is unknown is that it's not a standard function and not available on your platform.
Hey I am trying to connect to a database using postgres
#include <stdio.h>
#include <stdlib.h>
#include <libpq-fe.h>
int main(int argc, char* argv[])
{
//Start connection
PGconn* connection = PQconnectdb("host=webcourse.cs.nuim.ie dbname=cs621 sslmode=require user=ggales password=1234");
if (PQstatus(connection) ==CONNECTION_BAD)
{
printf("Connection error\n");
PQfinish(connection);
return -1; //Execution of the program will stop here
}
printf("Connection ok\n");
//End connection
PQfinish(connection);
printf("Disconnected\n");
return 0;
}
And I keep getting this compile error:
main.c: In function ‘main’:
main.c:9:35: warning: missing terminating " character [enabled by default]
main.c:9:2: error: missing terminating " character
main.c:10:2: error: ‘dbname’ undeclared (first use in this function)
main.c:10:2: note: each undeclared identifier is reported only once for each function it appears in
main.c:10:9: error: ‘cs621’ undeclared (first use in this function)
main.c:10:15: error: expected ‘)’ before ‘sslmode’
main.c:10:56: warning: missing terminating " character [enabled by default]
main.c:10:15: error: missing terminating " character
main.c:16:1: error: expected ‘,’ or ‘;’ before ‘}’ token
main.c:16:1: error: expected declaration or statement at end of input
Can anyone see why this is happening?
Thanks.
Your code compiles just fine. If I paste it into x.c I can compile it with no problems:
gcc -I /usr/pgsql-9.2/include -L /usr/pgsql-9.2/lib x.c -lpq
(paths may differ on your system).
you may use the 64-bit libpq.lib in a 32-bit program.
you can use a 32-bit libpq.lib or change you platform to x64.
a 32-bit client + 64-bit server can not work well.
Since yesterday, I've been facing a compiling error for my C project. The project itself consists on creating a service that will make some tasks.
I don't what has changed since yesterday, but this morning, my code can't compile anymore.
Here are the errors I have :
c:\path\main.c(56): error C2275: 'SERVICE_TABLE_ENTRY' : illegal use of this type as an expression
c:\program files\microsoft sdks\windows\v7.0a\include\winsvc.h(773) : see declaration of 'SERVICE_TABLE_ENTRY'
c:\path\main.c(56): error C2146: syntax error : missing ';' before identifier 'DispatchTable'
c:\path\main.c(56): error C2065: 'DispatchTable' : undeclared identifier
c:\path\main.c(56): error C2059: syntax error : ']'
c:\path\main.c(57): error C2065: 'DispatchTable' : undeclared identifier
c:\path\main.c(57): warning C4047: 'function' : 'const SERVICE_TABLE_ENTRYA *' differs in levels of indirection from 'int'
c:\path\main.c(57): warning C4024: 'StartServiceCtrlDispatcherA' : different types for formal and actual parameter 1
Here's the code concerned by these errors (from lines 45 to 58) :
int main(int ac, char *av[])
{
if (ac > 1)
{
if (!parse_args(ac, av))
{
aff_error(ARGUMENTS);
return EXIT_FAILURE;
}
}
SERVICE_TABLE_ENTRY DispatchTable[] = {{MY_SERVICE_NAME, ServiceMain}, {NULL, NULL}};
StartServiceCtrlDispatcher(DispatchTable);
return EXIT_SUCCESS;
}
And here's the code of my ServiceMain function :
void WINAPI ServiceMain(DWORD ac, LPTSTR *av)
{
gl_ServiceStatus.dwServiceType = SERVICE_WIN32;
gl_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
gl_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
gl_ServiceStatus.dwWin32ExitCode = 0;
gl_ServiceStatus.dwServiceSpecificExitCode = 0;
gl_ServiceStatus.dwCheckPoint = 0;
gl_ServiceStatus.dwWaitHint = 0;
gl_ServiceStatusHandle = RegisterServiceCtrlHandler(MY_SERVICE_NAME, ServiceCtrlHandler);
if (gl_ServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)
return;
gl_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
gl_ServiceStatus.dwCheckPoint = 0;
gl_ServiceStatus.dwWaitHint = 0;
SetServiceStatus(gl_ServiceStatusHandle, &gl_ServiceStatus);
}
I couldn't manage to find some answers that fit my problem, could anyone helps ? Thanks !
When you name your source files *.c, MSVC assumes it's compiling C, which means C89. All block-local variables need to be declared at the beginning of the block.
Workarounds include:
declaring/initializing all local variables at the beginning of a code block (directly after an opening brace {)
rename the source files to *.cpp or equivalent and compile as C++.
upgrading to VS 2013, which relaxes this restriction.
You might be using a version of C that doesn't allow variables to be declared in the middle of a block. C used to require that variables be declared at the top of a block, after the opening { and before executable statements.
Put braces around the code where the variable is used.
In your case that means:
if (ac > 1)
{
if (!parse_args(ac, av))
{
aff_error(ARGUMENTS);
return EXIT_FAILURE;
}
}
{
SERVICE_TABLE_ENTRY DispatchTable[] = {{MY_SERVICE_NAME, ServiceMain}, {NULL, NULL}};
StartServiceCtrlDispatcher(DispatchTable);
}
This error occurred when transferring a project from one installation to another (VS2015 => VS2010).
The C code was actually compiled as C++ on the original machine, on the target machine the "Default" setting in Project Properties\C/C++\Advanced\Compile as was somehow pointing to C even though the source file was of type *.cpp.
In my small program, errors popped up regarding the placement in code of certain types e.g. HWND and HRESULT as well as on the different format of for loops , and C++ constructs like LPCTSTR, size_t, StringCbPrintf and BOOL. Comparison.
Changing the "Compile as" from Default to Compile as C++ Code (/TP) resolved it.
This will also give you "illegal use of this type as an expression".
WRONG:
MyClass::MyClass()
{
*MyClass _self = this;
}
CORRECT:
MyClass::MyClass()
{
MyClass* _self = this;
}
You might be wonder the point of that code. By explicitly casting to the type I thought it was, when the compiler threw an error, I realized I was ignoring some hungarian notation in front of the class name when trying to send "this"
to the constructor for another object. When bug hunting, best to test all of your assumptions.