Why do I keep getting the error message "Conflicting types for 'sleep'" when I try running my program?
#include <stdio.h>
#include <stdlib.h>
void congratulateStudent (char *student, char *course, int numDays)
{
printf("%s has done as much %s Programming as I could fit into %d days. \n", student, course, numDays);
}
int main(int argc, const char * argv[])
{
congratulateStudent("Mark", "Cocoa", 5);
sleep(2);
congratulateStudent("Bo", "Objective-C", 2);
sleep(2);
congratulateStudent("Mike", "Python", 5);
sleep(2);
congratulateStudent("Ted", "iOS", 5);
return 0;
}
Every library function has a corresponding header file that declares the function. For the sleep function, that header file is unistd.h. The documentation for each function tells you which header file to use.
If you don't include the correct header file, then the compiler will complain bitterly. Don't make the compiler unhappy, always include the correct header file.
Related
I'm trying to use the snprintf function which based on the manual I've read is apart of the <stdio.h> header however I'm getting an error that it's been implicitly declared. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct users {
char* user_id;
};
typedef struct users users_t;
int save_user_detail(user_t);
int main() {
users_t users;
save_user_detail(users);
return 0;
}
int save_user_detail(users_t users)
{
printf("Type the filename = ");
scanf("%s", users.user_id);
char* extension = ".txt";
char fileSpec[strlen(users.user_id)+strlen(extension)+1];
FILE *file;
snprintf(fileSpec, sizeof(fileSpec), "%s%s", users.user_id, extension);
file = fopen(fileSpec, "w");
if(file==NULL)
{
printf("Error: can't open file.\n");
return 1;
}
else
{
printf("File written successfully.\n");
fprintf(file, "WORKS!\r\n");
}
fclose(file);
return 0;
}
You seem to be using gcc, but this compiler does not necessarily use the glibc, which is compliant with the C Standard and supports snprintf.
On the Windows architecture, you may be using the Microsoft C library, which in older versions did not have snprintf or renamed it as _snprintf.
Here are 2 ways you can try a work around your problem:
try using _snprintf instead of snprintf.
define snprintf manually after including <stdio.h> as
int snprintf(char *buf, size_t size, const char *fmt, ...);
The compiler should stop complaining about the missing prototype and if the runtime library does have a symbol for snprintf with a matching calling convention, it will link to it and the program should behave as expected.
My question is regarding an exercise of the book which I am using for learning C; head first. In the exercise we are learning to share functions between certain .c files. I am working in Xcode 8.2.1 and wanted to know whether Xcode can compile this exercise for me. I've got it to work correctly with the terminal, but I was wondering whether Xcode allows this compilation and that I've just got something wrong in my properties or something.
The program is a simple XOR-encryption program.
This are the files:
main.c:
#include <stdio.h>
#include "encrypt.h"
int main()
{
char msg[80];
printf("Type your message to be encrypted:\n");
while (fgets(msg, 80, stdin)) {
encrypt(msg);
printf("The encrypted message is like this: %s\n", msg);
encrypt(msg);
printf("The encrypted message is decrypted as: %s\n",msg);
printf("Type your message to be encrypted:\n");
}
}
encrypt.h:
#ifndef ENCRYPT_H_
#define ENCRYPT_H_
void encrypt(char *message);
#endif
encrypt.c:
#include "encrypt.h"
void encrypt(char *message)
{
while (*message) {
*message = *message ^ 31;
message++;
}
}
Now I get an error in the main.c file saying that there is a conflicting type for the function encrypt. This says to me that it sees encrypt as an int-valued function (by default). I think the problem is that the program does not see the encrypt function correctly, however I've given it acces to the correct header file with the correct declaration etc. So that makes me think there is some compiler problem.
Edit: The error messages are:
Semantic Issue Group:
PATH/message_hider/encrypt.h:9:6: Conflicting types for 'encrypt'
PATH/message_hider/main.c:17:9: Implicit declaration of function 'encrypt' is invalid in C99
Scenario :
A C application created in Netbeans IDE with below two files:
some_function.c
#include <stdio.h>
int function_1(int a, int b){
printf("Entered Value is = %d & %d\n",a,b);
return 0;
}
newmain.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
//function_2(); //Error //function name not allowed
function_1();
function_1(1);
function_1(1,2);
return (EXIT_SUCCESS);
}
When learning the need of the header file in a C program, I tried the above application (as it is). It got compiled and gave the output as below
Entered Value is = 4200800 & 102
Entered Value is = 1 & 102
Entered Value is = 1 & 2
Question 1 : (I realize, in starting stage, to understand the process of the linker program is tough, hence i ask this question.) Is my assumption correct, that when linking, "the linker will check for the function name and not the arguments" in a condition the header file not used?
Regarding the header file usage, I came across this link and there it said as, we can include the C file itself using the #include. So, I used the below line in the file newmain.c
#include "some_function.c"
As expected it shown the below error
error: too few arguments to function 'function_1()'
error: too few arguments to function 'function_1(1)'
And also, I got the below (unexpected) error:
some_function.c:8: multiple definition of `function_1'
some_function.c:8: first defined here
Question 2: What error I did when including the 'c' file itself, as it gives the above said (unexpected) error?
You are probably using a pre-C99 dialect of C, which has "implicit function declarations". This means that functions without declarations are taken to have this kind of signature:
int function_1();
i.e. returning an int and accepting any number of arguments of any type. When you pass an argument list that is incompatible with your function definition, you invoke undefined behaviour at runtime.
Concerning the multiple definition errors, think of it. Each translation unit you include some_function.c will have its own definition of the function. It is as if you had written that definition in every other .c file. C doesn't allow multiple definitions in a program/library.
I (the questioner) post this answer for a quick understanding for some C programming starters. This answer inspired from the answers by #juanchopanza & #Sam Protsenko which are in this post.
Question 1 :Implicit function declarations in C
Question 2:
When using the below line
#include "some_function.c"
The result application will change like below after the preprocessor activity
some_function.c
#include <stdio.h>
int function_1(int a, int b){
printf("Entered Value is = %d & %d\n",a,b);
return 0;
}
newmain.c
#include <stdio.h>
#include <stdlib.h>
/*"#include "some_function.c"" replace begin by preprocessor*/
#include <stdio.h>
int function_1(int a, int b){
printf("Entered Value is = %d & %d\n",a,b);
return 0;
}
/*"#include "some_function.c"" replace end by preprocessor*/
int main(int argc, char** argv) {
//function_2(); //Error //function name not allowed
//function_1(); //Error
//function_1(1); //Error
function_1(1,2);
return (EXIT_SUCCESS);
}
Note : In the above two file, the function function_1 is there in two places
So now the below error is meaningful
some_function.c:8: multiple definition of `function_1'
some_function.c:8: first defined here
The other answers on these questions say to declare the function either in a header file or before main() but I have both of these and it still doesn't work.
#include <stdbool.h>
#ifndef WORK
#define WORK
#define TRACING true
#define DIMENSION 4
#define TOUR_LENGTH 15
void trace(char *s); //error here "Conflicting types for 'trace'"
#endif
^that is the header file
void trace(char *s) //error here "Conflicting types for 'trace'"
{
if (TRACING)
{
printf("%s\n",s);
}
}
^the function in question. the function is used multiple times in other .c files all with #include work.h
#include <stdbool.h>
#include "work.h"
#include "gameTree.h"
#include "gameState.h"
#include "stack.h"
#include <stdio.h>
/*
* trace
* Provide trace output.
* Pre-condition: none
* Post-condition: if trace output is desired then the given String
* parameter is shown on the console
* Informally: show the given message for tracing purposes
*
* param s the String to be displayed as the trace message
*/
void trace(char *s) //error here "Conflicting types for 'trace'"
{
if (TRACING)
{
printf("%s\n",s);
}
}
/*
* intro
* Provide introductory output.
* Pre-condition: none
* Post-condition: an introduction to the progrm has been displayed
* Informally: give the user some information about the program
*/
void intro()
{
printf("Knight's Tour\n");
printf("=============\n");
printf("Welcome to the Knight's Tour. This is played on a(n) %d x %d board. The\n",DIMENSION,DIMENSION);
printf("knight must move %d times without landing on the same square twice.\n",TOUR_LENGTH);
printf("\n");
}
/*
* main
* Program entry point.
* Pre-condition: none
* Post-condition: the solution to the Knight's Tour will be found
* and displayed
* Informally: solve the Knight's Tour
*/
int main(int argc, char *argv[])
{
gameTree g,a; // whole game tree and solution game tree
gameState s; // initial game state
stack k,r; // stack for intermediate DF use and for tracing solution
queue q; // queue for intermediate BF use
// give introduction
intro();
// initialise data structures
init_stack(&k);
init_queue(&q);
init_gameState(&s, 1, 1); // start at top left-hand corner: (1,1)
// show initial board
printf("\nStarting board:\n");
showGameState(s);
printf("\n");
// solve
init_gameTree(&g, false, s, 1);
a = buildGameDF(g, k, TOUR_LENGTH); // Depth-first
//a = buildGameBF(g, q, TOUR_LENGTH); // Breadth-first
// show results
if (isEmptyGT(a))
{
printf("No solution!\n");
}
else
{
// re-trace solution from leaf to root
init_stack(&r);
do
{
push(r, a);
a = getParent(a);
} while (!isEmptyGT(a));
// display move list
while (!isEmptyS(r))
{
a = (gameTree)top(r);
s = (gameState)getData(a);
printf("Move %d: (%d,%d)\n", getLevel(a), getRow(s), getColumn(s));
pop(r);
}
// display final path
printf("\nFinal board:\n");
showGameState(s);
}
^the whole main() and .c file, the errors occur mainly in the other supplementary files with the ADT definitions such as:
gameTree getParent(gameTree t)
{
gameTree p;
trace("getParent: getParent starts"); //error here "Conflicting types for 'trace'" and "Implicit declaration of function 'trace' is invalid in C99"
if (isEmptyGT(t))
{
fprintf(stderr, "getParent: empty game tree");
exit(1);
}
init_gameTree(&p, true, NULL, -1);
p->root = getTNParent(t->root);
trace("getParent: getParent ends"); //error here "Conflicting types for 'trace'" and "Implicit declaration of function 'trace' is invalid in C99"
return p;
}
^an example of where the trace function is called.
#include <stdbool.h>
#include "tNode.h"
#include "gameTree.h"
#include "work.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
^the imports for one of the ADT .c files
So yeah I don't know what to do.
To clarify work.h and work.c are the main files for this project.
void setChild(gameTree t, gameTree c)
{
trace("setChild: setChild starts"); //error here "Implicit declaration of function 'trace' is invalid in C99"
setTNChild(t->root, c->root);
trace("setChild: setChild ends"); //but not here
}
void setTNSibling(tNode t, tNode n)
{
trace("setTNSibling: setTNSibling starts"); //both errors here
t->sibling = n;
trace("setTNSibling: setTNSibling ends"); //only the "Implicit declaration of function 'trace' is invalid in C99" error here
}
I can't determine what is causing certain errors but if it were to do with importing incorrect header files shouldn't it be consistent all the way through?
I should also note that these files were given to me to use so I didn't write the original trace function.
It is not clear from your code samples whether <ncurses.h> is included or not in some of your source files. There is a function trace already defined in <ncurses.h> on MacOS:
/usr/include/curses.h:1710:extern NCURSES_EXPORT(void) trace (const unsigned int);
If this is the actual problem, you need to rename your trace function to something else.
From the context, you should probably use a macro TRACE(...) that expands to a call to fprintf(stderr, __VA_ARGS__) unless you compile for the release build in which case it would expand to nothing at all.
Another potential cause for warnings is the prototype:
void trace(char *s);
Passing a string constant for a char * argument may cause a warning. Since trace does not modify the contents of the string argument, it should be declared const char *. Fix this by modifying the prototype:
void trace(const char *s);
gcc 4.4.2 c89
I re-engineering some code in c89. However, I am totally confused with the code that uses the following #defines. So I created a small application that maybe I would understand more of how this is working.
From what I can gather the MODULE_API will pass a function name and call the macro MODULE_SOURCE_API and concatenate name and func. So I create a simple function called print_name and ran the code. I got the following error messages:
implicit declaration of function ‘print_name’
undefined reference to `print_name'
What would be the main reason for doing this?
#include <stdio.h>
#define MODULE_SOURCE_API(name, func) name##_##func
#define MODULE_API(func) MODULE_SOURCE_API(mod_print, func)
void MODULE_API(print_name)(const char const *name);
int main(void)
{
printf("=== Start program ===\n");
print_name("Joe bloggs");
printf("== End of program ===\n");
return 0;
}
void MODULE_API(print_name)(const char const *name)
{
printf("My name is [ %s ]\n", name);
}
Many thanks for any advice,
EDIT ====
I have just made a correction I should be calling
MODULE_API(print_name)("Joe Bloggs");
But how can I print out what will be the outcome of concatenating? And what is the reason for doing this?
Many thanks,
#define MODULE_SOURCE_API(name, func) name##_##func
#define MODULE_API(func) MODULE_SOURCE_API(mod_print, func)
void MODULE_API(print_name)(const char const *name);
That will be producing a function named mod_print_print_name instead of print_name
You can check it on gcc with the -E option.
gcc -E ak.c gives
/* ...... */
void mod_print_print_name(const char const *name);
int main(void)
{
printf("=== Start program ===\n");
print_name("Joe bloggs");
printf("== End of program ===\n");
return 0;
}
void mod_print_print_name(const char const *name)
{
printf("My name is [ %s ]\n", name);
}
You can try to manually expand the macros to understand what is going on:
void MODULE_API( print_name )( const char * name ); // the second const there is redundant
// maybe you meant 'const char * const??
=(expand MODULE_API)=>
void MODULE_SOURCE_API( mod_print, print_name )( const char* name );
=(expand MODULE_SOURCE_API)=>
void mod_print_print_name( const char *);
As you see, the function being declared (and defined at the end of the code) is not print_name, but rather mod_print_print_name. Go back to the initial code and see how the macro is intended to be used. I would assume that function calls are performed with the same macros that are used for declarations and definitions.