How to include both for loop initial declarations and gnu extensions? - c

I have this code:
#include <string.h>
#include <stdio.h>
char numbers[5] = "12345";
int main(){
memrchr(numbers,'2',5);
for(int i=0;i<5;i++){
printf("%d",i);
}
return 0;
}
It uses for loop inital declarations (for(int i) and gnu extensions (memrchr).
I am using the compiler gcc
The problem is that it doesn't seem to let both go through. I can either do
gcc program.c -o program
Which complains about the for loops, or I can do
gcc -std=gnu11 program.c -o program
Which complains about memrchr being undefined. (or rather it complains about the implicit declaration of the function)
How do I do both? Is it possible?

You need to define the _GNU_SOURCE feature-test macro before any library #include. A convenient way to do that is to put it in your command line:
gcc -std=c11 -D_GNU_SOURCE program.c -o program
Or you could put the #define at the very top of every file which needs it. (Putting them in the source file is probably better, but I've gotten into the habit of putting them in my Makefiles. YMMV.)
You can see the needed feature-test macros in the manpage for every C library function. For example, man memrchr includes:
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
memrchr(), rawmemchr(): _GNU_SOURCE
As that says, man feature_test_macros will tell you more.

Related

Why does my compiler think my readlink() is implicitly declared if I set the standard to c99 or c11?

I have toy code that looks like this
#include <stdlib.h>
#include <unistd.h>
int main()
{
readlink("/proc/self/exe", "/my/path", 128);
return EXIT_SUCCESS;
}
When I compile with
icc main.c -o helloworld
everything is fine but when I e.g. try
icc -std=c99 main.c -o helloworld
or
icc -std=c11 main.c -o helloworld
I get the error message
main.c(6): warning #266: function "readlink" declared implicitly
What is it about c11 (or c99) standards that induces this error?
The definition is wrapped in
#if defined __USE_XOPEN_EXTENDED || defined __USE_XOPEN2K
From the man page for readlink you need to set the proper source definition first.
The current POSIX definition can be set with gcc -std=c11 -D_POSIX_C_SOURCE=200809L
If you don't set everything correctly you get to hunt undefined behavior because sizeof(int) and sizeof(void*) aren't the same anymore. Implicit declarations really did need to go for 64 bit to become.
-std=gnu11 flips everything on. If you don't have to care if you accidentally use a gcc extension or not, just set it in your makefile and forget about it.

Why does GCC claim clock_gettime() implicitly declared, but the preprocessor is perfectly happy with a related macro?

I'm trying to measure the amount of time an operation is taking, as accurately as possible. My research led me to believe that clock_gettime() and friends is what I want.
However, I can't for the life of me get it to work. Consider this seemingly trivial example:
#include <time.h>
#include <unistd.h>
int main(void)
{
struct timespec t;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t);
return 0;
}
If I run that through the preprocessor, everything looks like it's just fine:
$ cpp time.c | tail -n10
# 1163 "/usr/include/unistd.h" 3 4
# 3 "time.c" 2
int main(void)
{
struct timespec t;
clock_gettime(2, &t);
return 0;
}
However, if I try to compile the preprocessed code, it won't:
$ cpp time.c > time-prep.c
$ cc -o time -Wall -std=c11 -lrt time-prep.c
/tmp/user/1000/cc00SdhB.o: In function `main':
time-prep.c:(.text+0x15): undefined reference to `clock_gettime'
collect2: error: ld returned 1 exit status
$
If I try to compile the original, it doesn't go any better:
$ cc -o time -Wall -std=c11 -lrt time.c
time.c: In function ‘main’:
time.c:6:18: error: storage size of ‘t’ isn’t known
time.c:7:2: warning: implicit declaration of function ‘clock_gettime’ [-Wimplicit-function-declaration]
time.c:7:16: error: ‘CLOCK_PROCESS_CPUTIME_ID’ undeclared (first use in this function)
time.c:7:16: note: each undeclared identifier is reported only once for each function it appears in
time.c:6:18: warning: unused variable ‘t’ [-Wunused-variable]
$
The man page for clock_gettime says that I need to
Link with -lrt (only for glibc versions before 2.17).
but as you can see, I'm already doing that. Adding or removing -lrt to cc doesn't seem to make any difference whatsoever in my case.
I have looked at /usr/include/time.h but don't see anything obvious that I am missing.
What (presumably trivial) incantation is missing for me to be able to use clock_gettime() in my code?
The Linux documentation for clock_gettime() specifies a feature-test requirement:
_POSIX_C_SOURCE >= 199309L
You could consider fulfilling that directly, perhaps via a #define directive at the very beginning of your code, since the code in fact does depend on it.
If you do not provide such a #define, then gcc may nevertheless do it for you, depending on the options you specify to it. By default, it will do. Likewise with -std=gnu99 or -std=gnu11. But you attempted to compile with -std=c11, which asks for strict(ish) compliance with C11. C11 does not define the needed POSIX feature-test macro.
You can define _GNU_SOURCE above any #include. There is an example:
$cat ./main.c
// Need for clock_gettime()
// Have to be at the begining of the file
#define _GNU_SOURCE
#include <time.h>
#include <unistd.h>
int main(void)
{
...
}

C language prototype creation

I have this block of code. I have to move the given function display_name() into another .c file, compile it, and find the error that was caused due to the migration of the function and correct it by creating a header file with a prototype. How can I do it?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char student[]="Rasmus Lerdorf";
void display_name()
{
printf("Student Name : %s",student);
}
int main()
{
display_name();
}
these are the changes i made but again i still get an error in the main.cpp. it doesnt allow me to include the displayname.h file.
displayname.h
void display_name(void);
displayname.cpp
#include <stdio.h>
#include "displayname.h"
char student[] = "Rasmus Lerdorf";
void display_name()
{
printf("Student Name : %s", student);
}
main.cpp
#include <stdio.h>
#include "displayname.h"
int main()
{
display_name();
}
errors are:
3 IntelliSense: identifier "display_name" is undefined c:\Users\konstantinos\Desktop\main\main.cpp 7 2 Cproject
2 IntelliSense: cannot open source file "displayname.h" c:\Users\konstantinos\Desktop\main\main.cpp 2 1 Cproject
Error 1 error C1083: Cannot open include file: 'displayname.h': No such file or directory c:\users\konstantinos\desktop\main\main.cpp 2 1 Cproject
Prototype functions work like this: for each set of functions that you write (except main) you need a definition and an implementation. Definitions are usually stored in header files (extension .h) whereas implementations are stored in source files (extension .c).
Here is an example of how you could arrange your code to solve your problem.
Definition: display.h
// This file contains the definitions of the functions which you want to call from another file
void display_name(void);
Implementation: display.c
#include "display.h"
#include <stdio.h>
static char student[]="Rasmus Lerdorf";
void display_name()
{ printf("Student Name : %s",student);
}
With both the definition defined and the desired implemented, now you can call the function from your main source file.
Implementation: main.c
#include "display.h"
#include <stdio.h>
int main()
{
display_name();
}
This is how you link together a prototype of a function and the implementation of a function. You can expand this by adding more prototypes to display.h, implementing those prototyped functions in display.c, and then calling them throughout your code.
To build, both of these .c files must be included in your build phase. If you build from the command line, you need to do something like this (I'm assuming that your compiler is gcc):
cc display.c main.c -o program
Hope this helps.
Your header file, let's call it displayname.h should contain the declaration:
void display_name(void);
It's usually also best to create an include guard, which avoids causing problems if a header is included more than once:
#ifndef DISPLAYNAME_H
#define DISPLAYNAME_H
void display_name(void);
#endif /* DISPLAYNAME_H */
Then, in your displayname.c, you would include that header plus any others needed by the function, and define your constant and the function:
#include <stdio.h>
#include "displayname.h"
char student[]="Rasmus Lerdorf";
void display_name()
{
printf("Student Name : %s",student);
}
And in your main.c, you would also include that header:
#include "displayname.h"
int main()
{
display_name();
return 0;
}
I don't know what compiler you are using, but if you're on a Unix-like system (Linux, Mac OS X, or something like msys or Cygwin under Windows), you would compile and link them as follows (you can replace cc with your specific compiler, such as gcc or clang, though on most systems cc should exist and point to the default compiler for that system):
cc -c -o displayname.o displayname.c
cc -c -o main.o main.c
cc -o myprogram main.o displayname.o
You could also abbreviate this as:
cc -o myprogram main.c displayname.c
I also recommend, when you are learning, to use the -Wall -Wextra -Werror flags, to give you as many warnings as possible, and not allow compilation to proceed if there are any warnings. To make this more convenient, so you don't have to type the whole command every time, you can define a simple Makefile; the following uses GNU make syntax, if you don't have GNU make let me know and I'll edit it to use a more portable syntax:
CFLAGS=-Wall -Wextra -Werror
myprogram: main.o displayname.o
cc -o $# $^
%.o: %.c
cc -c $(CFLAGS) -o $# $<
main.o: displayname.h
displayname.o: displayname.h
If you have this set up, you can just type make and it will recompile everything that it needs to.
edit: I see now from your comments that you are using Visual Studio, so the above tips on how to compile and link using cc and make are not relevant to you. It has been too long since I have used Visual Studio to walk you through that myself, but Microsoft has a reasonable walkthrough of how to create and build a project that you can follow. The tutorial is for C++, but it should work similarly for C, just keep in mind that files should be named .c if they are written in C, and only .cpp if they are written in C++.
i did what you said! i created the 3 specific files displayname.h for the prototype , displayname.cpp in which the function display_name() stays and main.cpp in which i call the function display_name(). the problem again is that when i include the file displayname.h in the displayname.cpp it works fine, but when i include it in the main.cpp i have an underline error in the include. what is wrong?

How to use M_LN2 from Math.h

I am trying to use the Constant M_LN2 from the math.h library but always seem to get a compiler error. The code is:
#include <stdio.h>
#include <math.h>
int main(){
double x = M_LN2;
printf("%e",x);
return 0;
}
compiling with gcc on ubuntu
gcc -std=c99 lntester.c -o lntester -lm
getting output:
error: 'M_LN2' undeclared
any help in understanding why this is happening would be greatly appreciated.
As stated below the if def were not getting defined and using gcc and c99 were causing the issue. Below is the compile code that solved the issue and allowed me to use c99.
gcc -std=c99 -D_GNU_SOURCE lntested.c -o lntester -lm
any help in understanding why this is happening would be greatly
appreciated.
You can open /usr/include/math.h and try to found definition of M_LN2. For me it is defined and wrapped by condition macros:
#if defined __USE_BSD || defined __USE_XOPEN
...
# define M_LN2 0.69314718055994530942 /* log_e 2 */
...
#endif
When you compile your code with option -std=c99 neither __USE_BSD no __USE_XOPEN defined, so all variables which wrapped by if define not defined too.
You can compile your code without -std=c99 option or with -std=gnu99 option instead.

Error when compiling with GCC

Every time I compile I get the following error message:
Undefined reference to ( function name )
Let's say I have three files: Main.c, printhello.h, printhello.c. Main.c calls function print_hello(), which returns "Hello World". The function is defined in printhello.c.
Now, here's the following code of printhello.h:
#ifndef PRINTHELLO_H
#define PRINTHELLO_H
void print_hello();
#endif
I am sure this code is fine. I still don't know why is it giving me the error, though. Can you help me?
Undefined references are the linker errors. Are you compiling and linking all the source files ? Since the main.c calls print_hello(), linker should see the definition of it.
gcc Main.c printhello.c -o a.out
The error is, I think, a linker error rather than a compiler error; it is trying to tell you that you've not provided all the functions that are needed to make a complete program.
You need to compile the program like this:
gcc -o printhello Main.c printhello.c
This assumes that your file Main.c is something like:
#include "printhello.h"
int main(void)
{
print_hello();
return 0;
}
and that your file printhello.c is something like:
#include "printhello.h"
#include <stdio.h>
void print_hello(void)
{
puts("Hello World");
}
Your declaration in printhello.h should be:
void print_hello(void);
This explicitly says that the function takes no parameters. The declaration with the empty brackets means "there is a function print_hello() which returns no value and takes an indeterminate (but not variadic) list of arguments", which is quite different. In particular, you could call print_hello() with any number of arguments and the compiler could not reject the program.
Note that C++ treats the empty argument list the same as void print_hello(void); (so it would ensure that calls to print_hello() include no arguments), but C++ is not the same as C.
Another way to do it is to explicitly build object files for the printhello:
gcc -c printhello.c -o printhello.o
gcc -o Main main.c printhello.o
This has the added benefit of allowing other programs to use the print_hello method
It seems that the error is from the linker and not the compiler. You need to compile and link both the source files. I think what you are doing is simply including the header file in Main.c and you are not compiling the printhello.c
You need to :
gcc Main.c printhello.c -o myprog
or
construct the object files first
gcc -c printhello.c
gcc -c Main.c
then link them
gcc Main.o printhello.o

Resources