Using non-standard functions in Code::Blocks - c

I got this book "Beginning C" by Ivor Horton and I'm half way through it and I like it; so far so good. I use Code::Blocks on Windows as my IDE, and now I've run into the problem I cannot solve for about 3 days now.
The author mentions some "optional" functions in <string.h>, like strnlen_s(), and also says that these are available in the new standard — C11 (the book is from 2013; I don't know how new C11 actually is), and he also gives a piece of code that will determine "whether the standard library that comes with your C compiler supports these optional functions".
This is the code:
#include <stdio.h>
int main(void)
{
#if defined __STDC_LIB_EXT1__
printf("Optional functions are defined.\n");
#else
printf("Optional functions are not defined.\n");
#endif
return 0;
}
So I run the code to check if GCC in Code::Blocks does and determine that it doesn't. The book didn't recommend the compiler nor the IDE; I picked up Code::Blocks with GCC on my own, since that's what I do my exams in at college, so I figured I should get familiar with the environment.
The thing is, I have no idea how to "fix" this, since strnlen() doesn't work, strnlen_s() doesn't work, and bunch of others, and I can't really continue through a book. Not that I need them, or that I can't do it any other way (strlen() works just fine) but it would be nice to know how to use non-standard functions.

Up to date versions of GCC certainly do support C11, you need to enable it with the compiler flag -std=c11.
I presume you're using some flavour of MinGW with Code::Blocks - I recommend using MinGW-W64 as it is actively maintained and very up to date.
Also, bundled toolchains of MinGW-W64's gcc are available at TDM-GCC.
The Code::Blocks IDE itself doesn't care which version of C you're using, that doesn't affect what libraries you have available.

You are speaking of the optional Annex K Microsoft pushed through.
K.2 Scope
1 This annex specifies a series of optional extensions that can be useful in the mitigation of
security vulnerabilities in programs, and comprise new functions, macros, and types
declared or defined in existing standard headers.
2 An implementation that defines __STDC_LIB_EXT1__ shall conform to the
specifications in this annex.380)
3 Subclause K.3 should be read as if it were merged into the parallel structure of named
subclauses of clause 7.
It is generally seen as deeply flawed, and Microsoft trying to force it's use as a severe nuisance.
That's especially the case as they are the only major player implementing them, and their versions are non-conformant.
glibc with gcc for example provide most supposed advantages of that annex without introducing new functions, discouraging use of half the standard-library and forcing such a cumbersome API on programmers.
You might want to read the C tag-wiki, and especially grab a draft of the C11 standard (which is from 2011, as the name should imply).

The optional Annex K from the C11 Standard is not widely adopted yet (see Deduplicator's comment below). For instance as of February 2015 it hasn't been merged into glibc.
The good news is that you might try an alternative compiler. For instance Pelles C for Windows is a modified LCC with enhanced support for newest C11 features (like atomics and C11 threads model, that I believe are also mentioned in your book). Here is some basic program, that compiles and runs in it:
#include <stdio.h>
#include <string.h>
int main(void)
{
#if defined __STDC_LIB_EXT1__
printf("Optional functions are defined.\n");
#else
printf("Optional functions are not defined.\n");
#endif
char *str = "Hello Annex K";
printf("%zu\n", strnlen_s(str, 5));
return 0;
}
Output is:
Optional functions are defined.
5
Press any key to continue...

Related

__STDC_LIB_EXT1__ availability in gcc and clang

Since a quick Google search did not find anything, I will try to ask here (since many people involved in gcc/clang hang around here) - What is the status of __STDC_LIB_EXT1__ in gcc/clang? We are developing a cross platform applicataion and I wanted to use some of the safe bounds checking functions from <stdio.h> (which by miracle are available on Visual Studio 2017), but could not compile the code with Xcode 9.2. I assumed maybe the clang version Xcode uses is outdated, but gcc 6.3.0 on Ubuntu behaves the same. I am trying to use tmpnam_s with the following sample:
#if defined(__STDC_LIB_EXT1__)
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#else
#error "__STDC_LIB_EXT1__ not defined"
#endif
int main(int argc, char** argv)
{
char t[L_tmpnam_s];
tmpnam_s(t, L_tmpnam_s);
return 0;
}
But the compilation fails with the macro not being defined:
gcc -std=c11 test.c
test.c:5:2: error: #error "__STDC_LIB_EXT1__ not defined"
#error "__STDC_LIB_EXT1__ not defined"
^~~~~
Am I doing something wrong or this function set is simply poorly supported?
The whole set of 'safe' functions with the _s suffixes is poorly supported. Microsoft wrote a set of functions with the _s suffixes and submitted that to the C standard committee to be standardized. The committee made some changes (arguably out of necessity), and created a technical report, TR 24731-1. A mildly modified version of the TR was included as optional Annex K (normative) in the C11 standard, ISO/IEC 9899:2011.
You can find many sordid details in the answers to Do you use the TR-24731 "safer" functions?, especially in the notes in my answer to that question, and especially the link to the Standard C committee document N1967 Field Experience with Annex K — Bounds Checking Interfaces.
I don't know what the current status of the N1967 proposal is, but that it was suggested is telling. N1967 also contains links to libraries that support Annex K / TR-24731-1 — the list is limited.
Note that Microsoft does not implement the library specified by the C11 standard. It implements an approximation to the standard, but there are crucial differences. This would matter more if any other system had implemented the standard — but the functions have not been implemented in any widely accepted form (so, for example, the GNU C Library does not and will not support them).

How to install C11 compiler on Mac OS with optional string functions included?

I'm trying the below code to see if the optional string functions in C are supported (I've got Mac OS X El Capitan and XCode installed)...
#include <stdio.h>
int main(void)
{
#if defined __STDC_LIB_EXT1__
printf("Optional functions are defined.\n");
#else
printf("Optional functions are not defined.\n");
#endif
return 0;
}
...but it suggests they aren't.
I've tried all the different compilers I have from XCode (cc, gcc, llvm-gcc, clang).
I've also tried brew install gcc assuming that the GNU C compiler would give me these extra functions, but it doesn't.
Is there a way to simply install a C11 compatible compiler on Mac OS that'll give me these additional (i.e. safe) string functions.
Summary: You won't get it to work. There are better ways to make sure your code is correct. For now, use the address sanitizer instead.
Also known as "Annex K" of the C11 standard or TR 24731, these functions are not widely implemented. The only commonly available implementation is part of Microsoft Visual Studio, other common C implementations have rejected (explicitly, even) the functionality in annex K. So, while annex K is technically part of the standard, for practical purposes it should be treated as a Microsoft-specific extension.
See Field Experience With Annex K — Bounds Checking Interfaces (document N1967) for more information. According to this report, there are only four implementations of annex K, two are for Windows, one is considered "very incomplete" and the remaining one is "unsuitable for production use without considerable changes."
However, the argument that these string functions are "safe" is a bit misleading. These functions merely add bounds checking, which only works if the functions are called correctly—but then again, the "non-safe" functions only work if they are called correctly too. From the report cited above,
Despite more than a decade since the original proposal and nearly ten years since the ratification of ISO/IEC TR 24731-1:2007, and almost five years since the introduction of the Bounds checking interfaces into the C standard, no viable conforming implementations has emerged. The APIs continue to be controversial and requests for implementation continue to be rejected by implementers.
The design of the Bounds checking interfaces, though well-intentioned, suffers from far too many problems to correct. Using the APIs has been seen to lead to worse quality, less secure software than relying on established approaches or modern technologies. More effective and less intrusive approaches have become commonplace and are often preferred by users and security experts alike.
Therefore, we propose that Annex K be either removed from the next revision of the C standard, or deprecated and then removed.
I suggest using the address sanitizer as an alternative.
Do not use strncpy, strncat or the like as "safe" functions, they're not designed to do that and they are not drop-in replacements for strcpy, strcat, etc., unlike strcpy_s, strcat_s, which are drop-in replacements.
If you are not using Windows or Embarcadero you need to use the external safeclib: https://github.com/rurban/safeclib/releases
No other libc's comes with the safe C11 Annex K extensions.
For an overview of the various libc quirks regarding this see https://rurban.github.io/safeclib/doc/safec-3.3/d1/dae/md_doc_libc-overview.html

fatal error: thread.h: No such file or directory

Is there any way to access thread.h file .
I am not able to find thread.h header in windows since threading is related to OS.
I tried using pthread.h an external library , but was never able to find thread.h which according to my professor works in solaris.
This is an excellent example where tagging a question with "C" and "C++" is highly confusing because the answers are entirely different.
If you are coding in C++11 or later, then you should
#include <thread>
and use the std::thread class. You'll be fine.
If you are coding in C11 or later, then you should
#include <threads.h>
However, you may have to wait until your implementation supports it. § 7.26.1 ¶ 2 of the C11 standard says:
Implementations that define the macro __STDC_NO_THREADS__ need not provide this header nor support any of its facilities.
You can check with an #ifdef whether your implementation defines it. At least my GCC does.
For the time being, if you cannot switch to C++, use a third-party threading library like pthreads.
thread.h isn't well defined in the context of c++ standards. If you have a c++11 compliant toolchain, you need to
#include <thread>
as stated in the reference documentation.
Pre standard toolchains probably need to have the standard specified explicitly using the -std=c++0x or -std=c++11 compiler flags.
As you changed your focus to c, including c++ headers won't work. You may try pthread.h.

clang c11 threads.h not found

I am trying to setup a c11 thread example in xcode... but it doesn't seem to have the threads.h header, though it isn't complaning about the macro described here:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
__STDC_NO_THREADS__The integer constant 1, intended to indicate that the implementation does not support the <threads.h> header.
Looks like almost nothing supports the threads feature in C11... maybe I will try to get it into clang...
With the clang on my machine (v. 3.2 on ubuntu/linux) that feature test macro isn't defined. Support for that feature will need support in the C library, that usually doesn't come with the compiler. So basically the answer for clang will not be much different than for gcc, they usually build upon the same C library, namely glibc, see here for answer for gcc.
Just in case anyone is looking this up in 2021+, Apple still doesn't support this, and likely never will. As others have stated, pthreads is by far the best bet. Note that widely, C11 threads are not supported. I would go as far as to say pthreads is more portable in most circumstances.
From a development perspective, C11 threads are much too limited, and obfuscate user space vs. kernel space implementation features, along with implementation attributes.
If you really need C11 threads I would recommend doing one of three things.
Don't.
Use a cross-platform library: https://github.com/tinycthread/tinycthread seems to do a good job.
Write your own polyfill. The library I just mentioned tries to support a bunch of platforms (though it's inactive now), but anyone with a little bit of experience with pthreads and win32 threads will have no trouble (but, maybe a headache) writing a polyfill. I actually did this the other day out of interest, and it took just a few hundred lines, not too bad. For any project that will use it alot, this will give more control over usage.
The good thing to note is some other C11 features are supported on OSX, like C11 Atomics, which complementing would be impossible without a lot of ASM knowledge.
it doesn't seem to have the threads.h header, though it isn't complaining
C11 has 2 specs about __STDC_NO_THREADS__
7.26 Threads
Implementations that define the macro __STDC_NO_THREADS__ need not provide
this header nor support any of its facilities. C11 N1570 §7.26.1 2
__STDC_NO_THREADS__ The integer constant 1, intended to indicate that the
implementation does not support the <threads.h> header. C11 N1570 §6.10.8.3 1
Per §7.26.1 2:
#ifdef __STDC_NO_THREADS__
#error "No threading support"
#else
#include <threads.h>
#endif
Per §6.10.8.3:
#if defined(__STDC_NO_THREADS) && __STDC_NO_THREADS__ == 1
#error "No threading support"
#else
#include <threads.h>
#endif
// Certainly this can be simplified to
#if defined(__STDC_NO_THREADS) && __STDC_NO_THREADS__
or per What is the value of an undefined constant used in #if? to
#if __STDC_NO_THREADS__
This matches OP's code, so I would have expected that to work with a compliant C11 compiler.
Yet it looks like OP has a solution per #Kevin. That may be a false solution as __STDC_NO_THREADS looks like a typo (missing trailing __).
#if !defined(__STDC_NO_THREADS) || __STDC_NO_THREADS__
In C++11, you want to #include <thread>, not threads.h
#include <iostream>
#include <thread>
void fun() { std::cout << "fun!" << std::endl; }
int main() {
std::thread t ( fun );
t.join ();
return 0;
}

How many styles of writing functions are there in C?

So far, I know two styles:
/* 1st style */
int foo(int a) {
return a;
}
/* 2nd style */
int foo(a)
int a;
{
return a;
}
(I saw someone writing codes in the 2nd style. I was surprised at first but the 2nd style worked (under gcc as I tested). This made me curious and i wanted to ask this question.)
I won't call these styles, but languages variants (or dialects).
A coding style is a set of optional conventions that might not be followed. For instance, some coding styles request that macro names are all capitals (but your code will compile if you don't follow that rule).
Your "2nd style" is called Kernighan & Ritchie C. It is the old C defined in the late 1970s (in the very first edition of a famous book on C by Kernighan and Ritchie; subsequent editions have been conforming to later C standards). It is an obsolete language.
Current compilers are often following the C99 ISO standard (published in 1999), which has been replaced by the new C11 standard (published in 2011).
GCC compilers are accepting the C99 standard with the -std=c99 program argument. I strongly suggest to compile with gcc -Wall -std=c99; Recent GCC compilers (ie 4.6 and 4.7) are accepting -std=c11 IIRC for the newer standard C11.
Don't code today in the old Kernighan and Ritchie C dialect: it is obsolete, and less and less supported by compilers. IMHO C99 is a good standard to follow if you are cautious. And take profit of some of its features (in particular, ability to mix declarations and statements inside a block; older C dialects required to put all the declarations at the start of a block.).
The standard has progressed, in particular because it added features and is more precise w.r.t. to current systems and practices (e.g. multi-core processors)
There are (at least) two disadvantages when using the 2nd style:
If the function prototype is also missing, the compiler will not check for proper argument type. And, if I remember correctly, the number of arguments will also not be checked.
This (K&R, 1st Ed) style is valid only for backward compatibility ... someday, the C standard will (perhaps) disallow this style and your programs will halt.
Also, for better readability, you can put function's return type on its own line (especially useful with long-winded return types like unsigned long int and headers):
int
foo(int a)
{
return a;
}
The second style is the older style and is supported for backwards compatibility. I don't know of any other styles off the top of my head, but you should use the first (newer) style. The second (older) style was already deprecated when I started working with C (1994).
The 2nd one is K&R C style syntax, but it is obsolete now. Checkout #Basile Starynkevitch's answer.

Resources