C; headers and code - c

I'm beginner in C programming, so I have question about basic stuff.
When I work with non-standard packages and include their headers into my projects, I'm always getting "undefined reference to function" errors. I see that header files don't contain internal code of functions, and I'm guessing that I need to link headers with the code somehow. So my question is, should I search for some libraries like dlls, which contain the functions, or should I look for C source files, and in any case, how I'm gonna link them with headers and put them all together to work in my project? I'm using CodeBlocks + MinGW.

You need to build (actually link with the library) your executable against the external library you are using which you can specify using the -L path to lib gcc flag.
e.g
gcc -L path_to_lib -llib prog.c -o executable
you can use locate lib_name to know the path of the library.

When ever you have a header file in C you will have the header file Example:
//func.h
int myfunc(int x);
then you will have a source file
Blockquote
//func.c
#include "func.h"
int myfunc(int x)
{
return x;
}
Then your source file that has main()
//main.c
#include "func.h"
int main(){
int x = 2;
x = myfunc(x);
return x;
}
in your ide you include main.c and func.c in your source files. And include func.h in your header files.
I don't use code block, but basically any ide would work this way.

Related

Which files to add in CMake build scripts?

This is maybe a simple question. Let's give one example of .c program:
#include <stdio.h>
#include "Example.h"
int main(){
int x;
return 0;
}
If I have some C code which includes some .h file, i.e "Example.h" and in that header file are declared some functions which are implemented in i.e. "Example.c". Now I want to build this example using CMake files. Do I need to include also "Example.c" file ("besides Example.h") in the build process(CMake file)?
In CMake you would have to define your source files for the executable you wish to create, and yes that would include Example.h and Example.c. For example:
add_executable(myprogram Example.c Example.h)
or something on the lines of:
set(SRCS "Example.c" "Example.h")
add_executable(myprogram ${SRCS})
The following link provides a good introduction to CMake:
https://cliutils.gitlab.io/modern-cmake/chapters/basics.html
Although:
CMake is smart, and will only compile source file extensions. The headers will be, for most intents and purposes, ignored; the only reason to list them is to get them to show up in IDEs.

How to install libxml2 for C in OS X?

how to install libxml2 in OS X?
EDITED:
main.c
#include <stdlib.h>
#include <libxml2>
int main() {
printf("Hello, world!");
return 0;
}
The output I get is:
error: 'libxml2' file not found
If you have Homebrew installed, you can install libxml2 using:
brew install libxml2
To use libxml2, or any shared library, you need to...
Include the right header files in your code.
Add the path to the header files.
Add the path to the shared libraries.
Add the shared library.
The libxml2 docs aren't the best, but there are some code examples to draw from. And from that we see we need to #include <libxml/component.h> where component is whatever piece of the library you're including. For example, if you want to write XML documents, it's #include <libxml/xmlwriter.h>.
#include <stdlib.h>
#include <libxml/xmlwriter.h>
int main() {
// Just something to demonstrate we can call functions and the linking worked
xmlTextWriterPtr writer = xmlNewTextWriterFilename("example.com", 0);
// Just something to do with the variable.
printf("%p\n", writer);
}
Then you need to find the header files. OS X comes with libxml2 installed, but it's in /usr/include/libxml2. So that needs to be added to the include path with a -I/usr/include/libxml2.
The headers contain the definitions of the various functions, but the real code lies in shared libraries. Those are in the normal location, but you have to tell the compiler it to use it with -lxml2. Fortunately they're in the default location, so we don't have to add to the normal search path for shared libraries (that would be -L/some/path/).
Put it all together...
cc -I/usr/include/libxml2 -lxml2 -Wall test.c

how I call a function in my source file including only header file in c?

I would like to know , if I have source file like this
#include <stdio.h>
int main()
{
printf("Hello world");
}
as I know header files contains only prototypes of functions. If it so how can my source file get the function printf ? If I don't include the source file where it has been declared?
thank you
The question is not clear, but there are 2 things which happen before a program gets created,
Compiling (requires prototypes / declarations)
Linking (requires definitions).
Header information is needed for knowing prototypes. Even this would compile fine:
int printf ( const char * format, ... );
int main()
{
printf("Hello world");
}
On linking there will be no issues because the printf function is found in the C standard library, so on linking it will look into the standard directories (of the compiler where the library is kept - bin/lib folder) and link the function.
The source only needs to know the prototype. The problem a programmer will have in this case:
int my_printf ( const char * format, ... );
int main()
{
my_printf("Hello world");
}
The above will compile, but when linking my_printf your code will not have a definition so it will give an error on linking.
Header file has the definitions declarations of the functions ( stdio.h has definition declaration for printf ). The actual function exists in the libraries and gets linked when you compile the code.
When it comes to using libraries, you include the header of the library in your code and you instruct the linker to link using the code files of that library(usually object files). For the standard libraries, the IDE usually instructs the linker to link to them by default.
Assuming you're using gcc as a compiler the standard libraries are linked by default and that is where the function definitions lie. If you'd like to see exactly which libraries are being linked you can pass gcc the -v option which will cause it to dump information about the default options it will use including the library paths and default libraries and object files that will be linked in.
If you give the -Wl,--verbose option, gcc will pass the --verbose to the linker which will dump exactly where it's looking for libraries, including both failed and successful searches
gcc -v foo.c -Wl,--verbose
The header file stdio.h would declare printf as an extern function, i.e., it is defined elsewhere. The compiler is happy as long as functions you use have a declaration. The linker is the one that resolves these dependencies.
A very useful thing to do when you start asking good questions like this is to play with some linker commands.
Assuming you're on *nix, once you have your executable file (lets call it foo), do:
ldd foo
You should see a list of libraries that were linked with while creating foo.
libc.so should be one among those. It contains the definition for printf among other things!
You can refer to this link to learn more

How to link two source files properly? undefined reference error

Ok so I am doing a final project for one of my classes and trying to do a bit extra and create multiple files to work with. I am coding inside of CodeBlocks. So far I have a main.c, levels.c, and levels.h for my files. Inside of the levels.c levelOne function, I put the printf statement as a test to make sure I could have the two files work with each other before I went forward in my coding. I got a "undefined reference to 'levelOne' when I compiled and ran the program.
Inside my main.c file:
#include <stdio.h>
#include <stdlib.h>
#include "levels.h"
int main()
{
levelOne();
return 0;
}
Inside my levels.h file:
#ifndef LEVELS_H_INCLUDED
#define LEVELS_H_INCLUDED
void levelSelect(char c);
void levelOne();
void levelTwo();
void levelThree();
void levelCustom(int difficulty);
#endif // LEVELS_H_INCLUDED
Inside my levels.c file:
void levelOne()
{
//level scope of 1 to 10
srand(time(NULL));
int randomNum = (rand() % 9)+1);
printf("the random number is: %i\n", randomNum);
}
levels.c is not getting passed into the compiler, are you sure you have included levels.c in the whole project? If not it will not link. You need a project if you want to compile multiple files. In CodeBlocks, the sources and the settings for the build process are stored in a project file <name>.cbp
Here is the User Manual
gcc levels.c main.c should link successfully. gcc main.c will only compile one file and try and link to create final executable and levelOne() will not be found. since it is in file levels.c
You need to include levels.h in levels.c as well or if a function (physically) above levelOne calls it, it is undefined.
Then compile it with gcc -Wall *.c -o myapp to compile and link all of the c files in that directory into myapp (or you can name them individually) with (almost) all warnings enabled. This is provided you have it in its own directory.
Once you get into larger projects with more code, you can compile individual .c files into .o object files with gcc -Wall -c somecode.c and then link all the objects with gcc *.o -o myapp. If it gets really large, you'll want a build system to help with rebuilding objects only when its code (or dependent code) changes (such as Makefiles, waf, and dare I say autotools).
I had this exact same problem, the solution is easy. Right click on levels.c and select properties. A properties window should come up select the "Build" tab tick compile file, link file, and in the box check debug and release. This should fix your problem.
Don't make the mistake of doing this with a header file because it will give you a "...h.gch: file not recognized: File format not recognized.." error.

function header and implementation in different files C

How do you have a header file for a function and the implementation of that function in different files? Also, how do you have main in yet another file and call this function?
The advantage is so that this function will then be an independent component which can be reused, right?
This is best illustrated by an example.
Say we want a function to find the cube of an integer.
You would have the definition (implementation) in, say, cube.c
int cube( int x ) {
return x * x * x;
}
Then we'll put the function declaration in another file. By convention, this is done in a header file, cube.h in this case.
int cube( int x );
We can now call the function from somewhere else, driver.c for instance, by using the #include directive (which is part of the C preprocessor) .
#include "cube.h"
int main() {
int c = cube( 10 );
...
}
Finally, you'll need to compile each of your source files into an object file, and then link those to obtain an executable.
Using gcc, for instance
$ gcc -c cube.c #this produces a file named 'cube.o'
$ gcc -c driver.c #idem for 'driver.o'
$ gcc -o driver driver.c cube.c #produces your executable, 'driver'
Actually you can implement any function in header files for better performance(when implementing libraries for example) as long are not referenced to a specific object(actually it won't compile that).
By the way even with that way, you have separate interface and implementation ;)
Of course you will have include gurads in you header files to avoid "multiple definition" errors.
In C/C++, non-inline functions should be defined only once. If you put function defination
in header files, you will get "multiple defination" link error when the header file is included more than once.

Resources