Delphi XE3: Using multiple C headers and source files - c

So, I have a set of interdependent .c and .h files, and I'm trying to figure out exactly how C/C++-to-Pascal works (my delphi/pascal work otherwise was pretty basic). The c files are steps 1-N (in order) of a mathematical algorithm (each one is a separate function), one header specifies the variables used in each function (I'm using record to recreate the .h files in delphi), and the other header details a custom variable type. The goal is to access the functions without having to re-write the C code into Pascal/Delphi syntax, linking from delphi code to some existing c. There are too many lengthy files (12 .c and 4 .h) for me to snip, and my C is horribly rusty, but I'll try.
For example, I have a file funcs.h:
#ifndef _FUNCS_H
#ifndef _FUNCS_H
#ifdef __cplusplus
extern "C" {
#endif
#include "New_Type.h" // custom variable used in funcs.h
#include "Optional.h" // optional set of more functions
typedef struct {
int a1[4];
double b1[10];
// Computed if optional functions are requested
double c1[10];
int d1[4];
} func1;
typedef struct {
new_type c2, d2;
} func2;
}
#endif
#endif
and files func1.c and func2.c do some mathematical manipulation (mostly linear algebra) of the above variables. My immediate questions are:
Do I need multiple delphi files, much like there are multiple C headers?
What do the delphi files' "skeletons" look like (premable, function calls)?
What is {$LINKLIB C}, cdecl, and CALLBACK? Their common in other question/answers I've seen
Maybe I need to change my search/question, but I'm honestly not sure how to properly ask this. I don't need a specific answer, honestly I'd prefer if someone could point me to some links (heck a book: I'll be using this language in the future), I'd really appreciate it.
Thanks in advance for all the help.

Starting with #2: In Delphi, both the header and the implementation go in the same file. So here's a basic skeleton of a class showing where your header stuff (.h) and implementation stuff (.c) will fit into the structure of a unit/file in Delphi.
unit Unit1;
interface
uses // List of header dependencies goes here...
// Stuff from the .h file will go here
implementation
uses // List of implementation dependencies goes here...
// Stuff from the .c file will go here
end.
Back to #1: It's not strictly necessary to have a 1:1 mapping of your C header files to Delphi files, but if that was a good level of granularity per file in C, it's probably going to work out similarly in Delphi. Unless you have a good reason to change it, I'd leave them mapped at one C header file to one Delphi file.
About.com has a pretty detailed section on Delphi development, the page, for example, on working with units could be a good starting point on learning about the structure of a Delphi file. I also find myself using DelphiBasics as a reference site a lot (though it's more aimed at methods than structures). And definitely do not discount the official documentation on Embarcadero's website. Their Language Guide section is practically a textbook on learning Delphi, and is sufficiently detailed to get the fundamentals of the language.
And then as far as #3: This could easily be several separate full questions on stack overflow if you want more depth. But in general, it sounds like you're looking at code for calling c code directly from Delphi. CDecl is one of the calling conventions (the one that happens to match c...) which specifies which order parameters are passed to methods. Read more about it in Embarcadero's documentation. $LINKLIB is used to link to a library (in this case the C library, which you would do if you're calling c code), and callback is roughly equivalent to a function pointer in c.
From the overall sound of your third sub-question, I'm guessing you've been reading up on how to use C code in a Delphi project, without having to re-write the C code into Pascal/Delphi syntax, linking from delphi code to some existing c library you don't want to re-write or convert. If that's your ultimate goal, to just link to your C library without rewriting it, this article on using C in FreePascal may be of good help. For the purposes of linking to C code, the differences between FreePascal and Delphi, both variants of Pascal, are going to be relatively negligible). Basically, you have to re-write or convert the c header into Pascal syntax so that Delphi knows what functions are in your C library, so you can call them. Dr. Bob has a good detailed page about using C dlls in Delphi if you're looking for more info about converting header files. Amongst other useful information about how type names match, there is an example on that page of automated tools that exist for converting c header files to delphi headers. It may be easier to use an automated tool to convert your header to delphi syntax, if your goal is just to call or utilize your existing c code from a Delphi application without fully porting the entire code-library to Delphi.
And for the sake of example, your header from your question, converted through Dr. Bob's HeadConverter tool, gives output like this: (the actual output is longer and includes code for loading your c code as a dll and some comments as well)
unit FILE1;
interface
uses
Windows;
{$INCLUDE "New_Type.h"}
{$INCLUDE "Optional.h"}
type
func1 = record
a1: Array[0..4-1] of Integer;
b1: Array[0..10-1] of Double;
c1: Array[0..10-1] of Double;
d1: Array[0..4-1] of Integer;
end {func1};
type
func2 = record
c2, d2: NEW_TYPE;
end {func2};
{...}
implementation
{...}
end.

Related

Using my linked list code in a new c program

Apologies in advance since this seems extremely basic.
I have my linked list file, linkedList.c, and I would like to include it in my new c file so that I don't have to code the whole linked list in again. In Java I just had to place it in the same folder and then I could create an object of the class linkedList in the new file however C doesn't seem to work this way. If I try to use
#include "linkedLIst.c"
at the start of my new file then I receive errors since main has now been defined twice along with my Boolean variable. How exactly do I go about solving this?
You could #include any kind of (syntactically valid) C code, but you generally should not (by convention) include a .c file. Read more about the C preprocessor.
In practice, you should consider making some library (to be linked for reuse), and separate your shared code into a .h header file (containing definitions) that you would #include for re-using and an implementation .c file. Of course don't define any main in the shared source code. In some simple cases and on some operating systems, you might also share a single (or some few) object file (and related header files).
Your shared header would declare functions and extern variables (and #define some macros). It could also contain the definition (with their body) of short static inline functions.
Your shared implementation would define these (and others) functions and variables.
C programming entails a lot of conventions (and you need to define your own ones). Look at existing examples (some free software source code from github, or from a Linux distribution). For reusable container libraries, look into glib (from GTK) and also sglib (which uses a lot of preprocessor tricks) and many others.
Because C does not have any notion of namespaces it is wise (for readability and other reasons) to have a consistent naming convention, e.g. starting all the public names (of functions and variables and macros in headers) of your library by some common prefix.
You need to define a header file, linkedList.h, and declare your linked list function prototypes in there, which you probably already have defined in you linkedList.c file. And then, you can use '#include linkedList.h' to reuse your code.

Howto create C-Header for Delphi/Free Pascal/Lazarus DLL - data types

For my application I need to create a DLL from Delphi (to be more precise Delphi compatible code written within Lazarus IDE compiled by free pascal under linux) using stdcall.
When using that DLL (for example in Matlab or so) one needs of course the meta information for passing the arguments - often realised with a header file.
I'm searching for a tool do to that running on the delphi source code. Something like h2pas-reverse.
My research yielded no results. As I think, there is no such tool, I'd like to find a table or other information, how the Delphi/Pascal data types are mapped to C types and how to work with records.
I have used the below construct to generate header files compatible with the C-mode compiler of Visual C++ 6 from Delphi 5 code when Delphi had the -JPH switch (see notes below).
Note that I have not used this since Delphi 5, but the switch has since then been expanded:
Somewhere along the line, the JPHNE switch has been added to the dcc32 command-line compiler:
-JPHNE = Generate C++ .obj file, .hpp file, in namespace, export all
Rudy Velthuis has a nice article using the JPHNE switch.
It certainly does not handle all types, and you will need quite a bit of HPPEMIT and EXTERNALSYM directives.
I uploaded my Delphi 5 to Visual C++ 6 HPP conversion from back then to BitBucket.
It generates the .hpp files to import the DLL that was written in Delphi.
Notes from the Delphi 5 era:
{ Visual C++ 6 does not like nested structs/unions the way that BC++ can handle them.
Visual C++ 6 requires the "typedef" to be present AND the typename AFTER the struct definition.
You will see this when defining TConversationId, TReturnKey and other types that depend on nested structs/unions
The trick is to perform these steps each and every time this unit changes:
- Generate this unit once with all the EXTERNALSYM disabled.
- Then the DCC32 -JPH will generate the basic structs for them.
- Copy all the nested struct and union definitions to this file
- Embed the definitions with (*$HPPEMIT '' *)
- Append the typename at the end of the struct definition
- Enable all the EXTERNALSYM again
- Regenerate the HPP files by using DCC32 -JPH
To make this process easier, we have introduced two new conditional defines:
- BCB - disable EXTERNALSYM, disable HPPEMIT
- VC6 - enable EXTERNALSYM, enable HPPEMIT
A similar thing is with these constructions that VC6 does not like those either:
- short strings (BCB defines them as "SmallString<##>" which VC6 does not like).
- short integers (BCB defines them as "Shortint" so we have included an HPPEMIT for that)
}
{$ifdef win32}
{ important! Makes sure that the all enumerated types fit in exactly one byte each! }
{$Z1}
{ force the C/C++ HPP header files to have the C/C++ compiler pack structure elements on byte boundaries }
{$ifdef BCB}
{$HPPEMIT '#pragma option push -a1' }
{$endif BCB}
{$endif win32}

What is a C header file? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
[C] Header per source file.
In C++ why have header files and cpp files?
C++ - What should go into an .h file?
Is the only reason header files exist in C is so a developer can quickly see what functions are available, and what arguments they can take? Or is it something to do with the compiler?
Why has no other language used this method? Is it just me, or does it seem that having 2 sets of function definitions will only lead to more maintenance and more room for errors? Or is knowing about header files just something every C developer must know?
Header files are needed to declare functions and variables that are available. You might not have access to the definitions (=the .c files) at all; C supports binary-only distribution of code in libraries.
The compiler needs the information in the header files to know what functions, structures, etc are available and how to use them.
All languages needs this kind of information, although they retrieve the information in different ways. For example, a Java compiler does this by scanning either the class-file or the java source code to retrieve the information.
The drawback with the Java-way is that the compiler potentially needs to hold a much more of information in its memory to be able to do this. This is no big deal today, but in the seventies, when the C language was created, it was simply not possible to keep that much information in memory.
The main reason headers exist is to share declarations among multiple source files.
Say you have the function float *f(int a, int b) defined in the file a.c and reused in b.c and d.c. To allow the compiler to properly check arguments and return values you either put the function prototype in an header file and include it in the .c source files or you repeat the prototype in each source file.
Same goes for typedef etc.
While you could, in theory, repeat the same declaration in each source file, it would become a real nightmare to properly manage it.
Some language uses the same approach. I remember the TurboPascal units being not very different. You would put use ... at the beginning to signal that you were going to require functions that were defined elsewhere. I can't remember if that was passed into Delphi as well.
Know what is in a library at your disposal.
Split the program into bite-size chunks for the compiler. Compiling a megabyte of C files simultaneously will take more resources than most modern hardware can offer.
Reduce compiler load. Why should it know in screen display procedures about deep database engine? Let it learn only of functions it needs now.
Separate private and public data. This use isn't frequent but you may implement in C what C++ uses private fields for: each .c file includes two .h files, one with declarations of private stuff, the other with whatever others may require from the file. Less chance of a namespace conflict, safer due to hermetization.
Alternate configs. Makefile decides which header to use, and the same code may service two different platforms given two different header files.
probably more.

A Java programmer has questions regarding C header files

I have a fair amount of practice with Java as a programming language, but I am completely new to C. I understand that a header file contains forward declarations for methods and variables. How is this different from an abstract class in Java?
The short answer:
Abstract classes are a concept of object oriented programming. Header files are a necessity due to the way that the C language is constructed. It cannot be compared in any way
The long answer
To understand the header file, and the need for header files, you must understand the concepts of "declaration" and "definition". In C and C++, a declaration means, that you declare that something exists somewhere, for example a function.
void Test(int i);
We have now declared, that somewhere in the program, there exists a function Test, that takes a single int parameter. When you have a definition, you define what it is:
void Test(int i)
{
...
}
Here we have defined what the function void Test(int) actually is.
Global variables are declared using the extern keyword
extern int i;
They are defined without the extern keyword
int i;
When you compile a C program, you compile each source file (.c file) into an .obj file. Definitions will be compiled into the .obj file as actual code. When all these have been compiled, they are linked to the final executable. Therefore, a function should only be defined on one .c file, otherwise, the same function will end up multiple times in the executable. This is not really critical if the function definitions are identical. It is more problematic if a global variable is linked into the same executable twice. That will leave half the code to use the one instance, and the other half of the code to use the other instance.
But functions defined in one .c file cannot see functions defined in another .c files. So if from file1.c file you need to access function Test(int) defined in file2.c, you need to have a declaration of Test(int) present when compiling file1.c. When file1.c is compiled into file1.obj, the resulting .obj file will contain information that it needs Test(int) to be defined somewhere. When the program is linked, the linker will identify that file2.obj contains the function that file1.obj depends on.
If there is no .obj file containing the definition for this function, you will get a linker error, not a compiler error (linker errors are considerably more difficult to find and correct that compiler errors because you get no filename and line number for the resulting file)
So you use the header file to store declarations for the definitions stored in the corresponding source file.
IMO it's mainly because many C programmers seem to think that Java programmers don't know how to program “for real”, e.g. handling pointers, memory and so on.
I would rather compare headers to Java interfaces, in the sense that they generally define how the API must be used.
Headers are basically just a way to avoid copy-pasting: the preprocessor simply includes the content of the header in the source file when encounters an #include directive.
You put in a header every declaration that the user will commonly use.
Here's the answers:
Java has had a bad reputation among some hardcore C programmers mainly because they think:
it's "too easy" (no memory-management, segfaults)
"can't be used for serious work"
"just for the web" or,
"slow".
Java is hardly the easiest language in the world these days, compared to some lanmguages like Python, etc.
It is used in many desktop apps - applets aren't even used that often. Finally, Java will always be slower than C, because it is not compiled directly to machine code. Sometimes, though, extreme speed isn't needed. Anyway, the JVM isn't the slowest language VM ever.
When you're working in C, there aren't abstract classes.
All a header file does is contain code which is pasted into other files. The main reason you put it in a header file is so that it is at the top of the file - this way, you don't need to care where you put your functions in the actual implementation file.
While you can kind-of use OO concepts in C, it doesn't have built-in support for classes and similar fundamentals of OO. It is nigh-impossible to implement inheritance in plain C, therefore there can never actually have OO, or abstract classes for that matter. I would suggest sticking to plain old structs.
If it makes it easier for you to learn, by all means think of them as abstract classes (with the implementation file being the inheriting class) - but IMHO it is a difficult mindset to use when for working in a language without explicit support of said features.
I'm not sure if Java has them, but I think a closer analogue could be partial classes in C#.
If you forward declare something, you have to actually deliver and implement it, else the compiler will complain. The header allows you to display a "module"'s public API and make the declarations available (for type checking and so) to other parts of the program.
Comprehensive reading: Learning C from Java. Recommended reading for developers who are coming from Java to C.
I think that there is much derision (mockery, laughter, contempt, ridicule) for Java simply because it's popular.
Abstract classes and interfaces specify a contract or a set of functions that can be invoked on an object of a certain type. Function prototypes in C only really do compile time type checking of function arguments/return values.
While your first question seems subjective to me, I will answer to the second one:
A header file contains the declarations which are then made available to other files via #inclusion by the preprocessor.
For instance you will declare in a header a function, and you will implement in a .c file. Other files will be able to use the function so long they can see the declaration (by including the header file).
At linking time the linker will look among the object files, or the various libraries linked, for some object which provides the code for the function.
A typical pattern is: you distribute the header files for your library, and a dll (for instance) which contains the object code. Then in your application you include the header, and the compiler will be able to compile because it will find the declaration in the header. No need to provide the actual implementation of the code, which will be available for the linker through the dll.
C programs run directy, while Java programs run inside the JVM, so a common belief is that Java programs are slow. Also in Java you are hidden from some low level constructs (pointer, direct memory access), memory management, etc...
In C the declaration and definition of a function is separated. Declaration "declares" that there exists a function that called by those arguments returns something. Definition "defines" what the function actually does. The former is done in header files, the latter in the actual code. When you are compiling your code, you must use the header files to tell your compiler that there is such a function, and link in a binary that contains the binary code for the function.
In Java, the binary code itself also contains the declaration of the functions, so it is enough for the compiler to look at the class files to get both the definition and declaration of the available functions.

Reading Recommendations To Learn Basics Of C

I'm now really diving into my OS project, called ForestOS, but now I'm needing to dive more into some simple and basic things of C. As now I'm having many problems with the correct variable to use and functions.
I want resources that only talk about variables, functions and how to develop without headers(stdio.h, math.h and all the others).
Best starting place is probably the book The C Programming Language.
The book was central to the development and popularization of the C programming language and is still widely read and used today.
A guide to OS development suggests CProgramming.com as the best place to start. There's tutorials, links to further resources, and everything for free.
Building an OS is non-trivial, I suggest if you are "having many problems with the correct variable to use and functions" then you may be attempting to walk before you can run!
Quote:
how to develop without headers(stdio.h, math.h and all the others).
I assume that you actually mean that you want to code without using the standard library rather than "without headers". Header files are intrinsic to modularisation in C; if you did not use headers, your code would have to be one monolithic module. Don't confuse headers with libraries.
However, even then there is no need not to use the standard library when writing 'bare-metal' code. You simply need a library that does not have OS dependencies, and you write the low level glue code to make things like stdio and memory allocation work on your system. Such a library is Newlib for example. It will make your life a whole lot easier if you have standard library support.
You only need headers to provide declarations of functions and external variables.
It is possible to eliminate the header files and provide your declarations within the translation unit (a.k.a. source file). Although possible, this is not recommended.
Here is an example of a legal C program without header files:
/* Forward declaration of main(). */
int main(void);
/* Definition for main() function. */
int
main(void)
{
return 13; /* 42 is such an overrated number. */
}
Some reasons for using header files are: code / typing reduction and single point of maintenance. If two modules need the same structure declaration, placing it in a header file will reduce typing (you only have to #include it in both files instead of copying it into both files). Also, if you need to change any declaration, if it is copied, you'll have to hunt down all copies and change every instance vs. making one change in a header file.
As far as standard header files, such as math.h and stdio.h, if you don't need them, don't include them. An OS should not require stdio.h, but may use math.h. Most standard header files do not contribute to the code size; only to the compile time.
I highly suggest you focus on the correctness of your OS and don't worry about trivialities such as header files. After your OS is working correctly and robust, go ahead and trim the fat.
Go through Kernighan C or the book named "Let Us C".It would help you learn much better as a beginner

Resources