How to compile in Xcode C file with C11 language dialect? - xcode

I want to compile this source code:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, const char *argv[]) {
While:
printf("MacBook-Pro-...:~ ...$ ");
char command[128];
gets_s(command);
if (strncmp(command, "exit", 4) == 0)
exit(0);
pid_t return_value = fork();
if (return_value == 0) {
int outfile;
if ((outfile = dup(1)) == -1)
return -1;
close(1);
if ((outfile = open("/Users/.../1.txt",
O_WRONLY | O_TRUNC | O_CREAT, 0644)) >= 0) {
execl("/bin/sh", "sh", "-c", command, NULL);
}
close(outfile);
exit(0);
} else {
wait();
FILE *fp;
char str[128];
fp = fopen("/Users/.../1.txt", "r");
while(!feof(fp)) {
if(fgets(str, 126, fp))
printf("%s", str);
}
fclose(fp);
goto While;
}
return 0;
}
But i have some errors:
Semantic Issue
Implicit declaration of function 'gets_s' is invalid in C99
Implicitly declaring library function 'exit' with type 'void (int) attribute((noreturn))'
Implicit declaration of function 'wait' is invalid in C99
Too few arguments to function call, expected 1, have 0
Project settings:
System:
ProductName: Mac OS X
ProductVersion: 10.12.1
BuildVersion: 16B2555
Xcode Version 8.0 (8A218a)
Apple LLVM version 8.0.0 (clang-800.0.38)
Target: x86_64-apple-darwin16.1.0
Thread model: posix

There are few problems:
Xcode doesn't see function definitions, that's why it says 'Implicit declaration of function 'foobar' is invalid in C99'. Even despite that Xcode attempts to compile your code assuming that unknown functions will be resolved during linking phase. In the case of exit and wait it will work, but to suppress the warning you just need to include stdlib: #include <stdlib.h>.
As of gets_s you need to do some extra actions to make it work (I don't know where it comes from).
Second problem is that signature of the wait function looks like this: int wait(int *), while you are not giving any parameters to it. Simply add 0 or NULL if you don't need to get exit code from a child process back.

Related

Error while building a static Linux binary (with musl-libc) that includes LuaJIT

I've cloned the LuaJIT git repo and built it with:
make STATIC_CC="musl-gcc" BUILDMODE="static"
Then, I compiled a simple Lua "hello world" script into a C header file:
luajit -b test.lua test.h
test.h:
#define luaJIT_BC_test_SIZE 52
static const unsigned char luaJIT_BC_test[] = {
27,76,74,2,10,45,2,0,3,0,2,0,4,54,0,0,0,39,2,1,0,66,0,2,1,75,0,1,0,20,72,101,
108,108,111,32,102,114,111,109,32,76,117,97,33,10,112,114,105,110,116,0
};
After that, I wrote a simple C wrapper by following the official example, test.c:
#include <stdio.h>
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include "test.h"
int main(void) {
int error;
lua_State *L = lua_open();
luaL_openlibs(L);
error = luaL_loadbuffer(L, (const char *) luaJIT_BC_test, luaJIT_BC_test_SIZE, "test") || lua_pcall(L, 0, 0, 0);
if (error) {
fprintf(stderr, "%s", lua_tostring(L, -1));
lua_pop(L, 1);
}
lua_close(L);
return 0;
}
But when I try to build it, it crashes with an error:
$ musl-gcc -static -ILuaJIT/src -LLuaJIT/src -o test test.c -lluajit
/usr/bin/ld: /usr/lib/gcc/x86_64-pc-linux-gnu/12.1.0/libgcc_eh.a(unwind-dw2-fde-dip.o): in function `_Unwind_Find_FDE':
(.text+0x1953): undefined reference to `_dl_find_object'
collect2: error: ld returned 1 exit status
It's related to libgcc, so I tried building everything with musl-clang, but still got the same error. Can someone explain what I'm missing here?
Figured it out - I needed to build LuaJIT with TARGET_XCFLAGS=-DLUAJIT_NO_UNWIND like so:
make STATIC_CC="musl-gcc" BUILDMODE="static" TARGET_XCFLAGS=-DLUAJIT_NO_UNWIND
I guess this just disables C++ exceptions support, but I'm not sure what the real implications are. Seems to work fine, for now.

How to enable the _Generic keyword

I have this test source:
#include <stdio.h>
int main()
{
int x;
printf("x=%d\n", _Generic('x', int: 1, default: 0));
return 0;
}
Compiling with c++ (from GCC 4.9.2) fails:
t.cpp: In function ‘int main()’:
t.cpp:7:33: error: expected primary-expression before ‘int’
printf("x=%d\n", _Generic('x', int: 1, default: 0));
^
t.cpp:7:41: error: expected primary-expression before ‘default’
printf("x=%d\n", _Generic('x', int: 1, default: 0));
^
t.cpp:7:51: error: ‘_Generic’ was not declared in this scope
printf("x=%d\n", _Generic('x', int: 1, default: 0));
The compiler arguments are:
c++ --std=c++11 t.cpp -o t
What am I doing wrong?
_Generic is a C11 feature. It is not present in C++ (any version at least up to C++14 - I don't really expect it to be added either).
If you want to use it, you'll need to write C code, and use a compiler that supports that standard (reasonably recent versions of gcc and clang do for example, using -std=c11).
If you want to write C++, use overloading or templates instead, for example:
#include <iostream>
int foo(int) { return 1; }
int foo(char) { return 0; }
int main()
{
std::cout << "x=" << foo('x') << std::endl;
}
This prints x=0 in C++, the foo(char) overload is the best match.
Note that there's difference between C and C++ that might trick you here too: 'x' is a char in C++. It's an int in C. So if _Generic had been implemented (maybe as an extension) by your compiler, chances are you'd get different output when compiling your example as C versus compiling as C++.
Here's the C++ form (forgive me for using the using directive, I know its bad form):
#include <iostream>
using namespace std;
template< typename T> T do_something(T argument) {
// Put here what you need
}
int main()
{
int x;
cout << "x" << (x = do_something(x));
return 0;
}
_Generic is C11, you're probably using a C++ compiler when you meant to use a C compiler.

Visual Studio 2010 (C++): suppress C4706 warning temporarily

When you compile the following C++ source file in Visual Studio 2010 with warning level /W4 enabled
#include <cstdio> // for printf
#include <cstring> // for strcmp
char str0[] = "Hello";
char str1[] = "World";
int main()
{
int result;
if (result = strcmp(str0, str1)) // line 11
{
printf("Strings are different\n");
}
}
you get the following warning
warning C4706: assignment within conditional expression
for line 11.
I want to suppress this warning exactly at this place. So I tried Google and found this page: http://msdn.microsoft.com/en-us/library/2c8f766e(v=VS.100).aspx
So I changed the code to the following - hoping this would solve the problem:
#include <cstdio> // for printf
#include <cstring> // for strcmp
char str0[] = "Hello";
char str1[] = "World";
int main()
{
int result;
#pragma warning(push)
#pragma warning(disable : 4706)
if (result = strcmp(str0, str1))
#pragma warning(pop)
{
printf("Strings are different\n");
}
}
It didn't help.
This variant didn't help either:
#include <cstdio> // for printf
#include <cstring> // for strcmp
char str0[] = "Hello";
char str1[] = "World";
int main()
{
int result;
#pragma warning(push)
#pragma warning(disable : 4706)
if (result = strcmp(str0, str1))
{
#pragma warning(pop)
printf("Strings are different\n");
}
}
To avoid one further inquiry: I cleaned the solution before each compilation. So this is probably not the fault.
So in conclusion: how do I suppress the C4706 exactly at this place?
Edit Yes, rewriting is possible - but I really want to know why the way I try to suppress the warning (that is documented officially on MSDN) doesn't work - where is the mistake?
Instead of trying to hide your warning, fix the issue it's complaining about; your assignment has a value (the value on the left side of the assignment) that can be legally used in another expression.
You can fix this by explicitly testing the result of the assignment:
if ((result = strcmp(str0, str1)) != 0)
{
printf("Strings are different\n");
}
In MSDN Libray: http://msdn.microsoft.com/en-us/library/2c8f766e(v=VS.100).aspx, There is the section as follows.
For warning numbers in the range 4700-4999, which are the ones
associated with code generation, the state of the warning in effect
when the compiler encounters the open curly brace of a function will
be in effect for the rest of the function. Using the warning pragma in
the function to change the state of a warning that has a number larger
than 4699 will only take effect after the end of the function. The
following example shows the correct placement of warning pragmas to
disable a code-generation warning message, and then to restore it.
So '#pragma warning' only works for an each function/method.
Please see the following code for more detail.
#include <cstdio> // for printf
#include <cstring> // for strcmp
char str0[] = "Hello";
char str1[] = "World";
#pragma warning(push)
#pragma warning( disable : 4706 )
void func()
{
int result;
if (result = strcmp(str0, str1)) // No warning
{
printf("Strings are different\n");
}
#pragma warning(pop)
}
int main()
{
int result;
if (result = strcmp(str0, str1)) // 4706 Warning.
{
printf("Strings are different\n");
}
}
The sane solution is to rewrite the condition to
if( (result = strcmp(str0, str1)) != 0 )
which will inform any C compiler that you really want to assign, and is almost certain to generate the same object code.
There is another solution which avoids the warning: the comma operator.
The main advantage here will be that you don't need parentheses so it's a bit shorter than the !=0 solution when your variable name is short.
For example:
if (result = strcmp(str0, str1), result)
{
printf("Strings are different\n");
}
There is a simple construction !! to cast a type to bool. Like this:
if (!!(result = strcmp(str0, str1)))
However, in some cases direct comparison != 0 might be more clear to a reader.

getline on MacOSX 10.6 crashing C compiler?

I'm having a really hard time getting an R library installed that requires some compilation in C. I'm using a Mac OSX Snow Leopard machine and trying to install this R package (here).
I've looked at the thread talking about getline on macs and have tried a few of these fixes, but nothing is working! I'm a newbie and don't know any C, so that may be why! Can anyone give me some tips on how I could modify files in this package to get it to install?? Anyhelp would be pathetically appreciated! Here's the error I'm getting:
** libs
** arch - i386
g++ -arch i386 -I/Library/Frameworks/R.framework/Resources/include -I/Library/Frameworks/R.framework/Resources/include/i386 -I/usr/local/include -D_FASTMAP -DMAQ_LONGREADS -fPIC -g -O2 -c bed2vector.C -o bed2vector.o
In file included from /usr/include/c++/4.2.1/backward/strstream:51,
from bed2vector.C:8:
/usr/include/c++/4.2.1/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the <X> header for the <X.h> header for C++ includes, or <iostream> instead of the deprecated header <iostream.h>. To disable this warning use -Wno-deprecated.
bed2vector.C: In function ‘int get_a_line(FILE*, BZFILE*, int, std::string&)’:
bed2vector.C:74: error: no matching function for call to ‘getline(char**, size_t*, FILE*&)’
make: *** [bed2vector.o] Error 1
chmod: /Library/Frameworks/R.framework/Resources/library/spp/libs/i386/*: No such file or directory
ERROR: compilation failed for package 'spp'
The easiest solution is probably to add a static definition for getline() to bed2vector.c. This might be good enough:
/* PASTE AT TOP OF FILE */
#include <stdio.h> /* flockfile, getc_unlocked, funlockfile */
#include <stdlib.h> /* malloc, realloc */
#include <errno.h> /* errno */
#include <unistd.h> /* ssize_t */
extern "C" ssize_t getline(char **lineptr, size_t *n, FILE *stream);
/* PASTE REMAINDER AT BOTTOM OF FILE */
ssize_t
getline(char **linep, size_t *np, FILE *stream)
{
char *p = NULL;
size_t i = 0;
if (!linep || !np) {
errno = EINVAL;
return -1;
}
if (!(*linep) || !(*np)) {
*np = 120;
*linep = (char *)malloc(*np);
if (!(*linep)) {
return -1;
}
}
flockfile(stream);
p = *linep;
for (int ch = 0; (ch = getc_unlocked(stream)) != EOF;) {
if (i > *np) {
/* Grow *linep. */
size_t m = *np * 2;
char *s = (char *)realloc(*linep, m);
if (!s) {
int error = errno;
funlockfile(stream);
errno = error;
return -1;
}
*linep = s;
*np = m;
}
p[i] = ch;
if ('\n' == ch) break;
i += 1;
}
funlockfile(stream);
/* Null-terminate the string. */
if (i > *np) {
/* Grow *linep. */
size_t m = *np * 2;
char *s = (char *)realloc(*linep, m);
if (!s) {
return -1;
}
*linep = s;
*np = m;
}
p[i + 1] = '\0';
return ((i > 0)? i : -1);
}
This doesn't handle the case where the line is longer than the maximum value that ssize_t can represent. If you run into that case, you've likely got other problems.
Zeroth question: Have you considered using a package manager like fink or MacPorts rather than compiling yourself? I know that fink has an R package.
First question: How is the R build managed? Is there a ./configure? If so have you looked at the options to it? Does it use make? Scons? Some other dependency manager?
Second question: Have you told the build system that you are working on a Mac? Can you specify that you don't have a libc with native getline?
If the build system doesn't support Mac OS---but I image that R's does---you are probably going to have to download the standalone version, and hack the build to include it. How exactly you do that depends on the build system. And you may need to hack the source some.

Interposing library: XOpenDisplay

I am working on a project where I need to change the behaviour of the XOpenDisplay function defined in X11/Xlib.h.
I have found an example, which should do exactly what I am looking for, but when I compile it, I get the following error messages:
XOpenDisplay_interpose.c:14: Error: conflicting types for »XOpenDisplay«
/usr/include/X11/Xlib.h:1507: Error: previous declaration of »XOpenDisplay« was here
Can anyone help me with that problem? What am I missing?
My program code so far - based on the example mentioned above:
#include <stdio.h>
#include <X11/Xlib.h>
#include <dlfcn.h>
Display *XOpenDisplay(char *display_name)
{
static Display *(*func)(char *);
Display *ret;
void* handle=NULL;
handle = dlopen ("XOpenDisplay_interpose.so", RTLD_LAZY);
if(!handle){
fprintf(stderr, "ERROR dlopen\n");
}
if(!func)
func = (Display *(*)(char *))dlsym(handle,"XOpenDisplay");
if(display_name)
printf("XOpenDisplay() is called with display_name=%s\n", display_name);
else
printf("XOpenDisplay() is called with display_name=NULL\n");
ret = func(display_name);
printf(" calling XOpenDisplay(NULL)\n");
ret = func(0);
printf("XOpenDisplay() returned %p\n", ret);
return(ret);
}
int XCloseDisplay(Display *display_name)
{
static int (*func)(Display *);
int ret;
void* handle=NULL;
handle = dlopen ("XOpenDisplay_interpose.so", RTLD_LAZY);
if(!handle){
fprintf(stderr, "ERROR dlopen\n");
}
if(!func)
func = (int (*)(Display *))dlsym(handle,"XCloseDisplay");
ret = (int)func(display_name);
printf("called XCloseDisplay(%p)\n", display_name);
return(ret);
}
int main()
{
}
Regards,
Andy.
The declaration reads like this:
Display *XOpenDisplay(_Xconst char *display_name)
So just adding a 'const' should suffice.

Resources