use variables from a C generated file - arrays

I have generated a C file which contains some arrays with their size as here:
nor.c (generated file)
const float nor[] = {
-0.0972819, 0.906339, -0.4112, -0.056471, 0.340899, -0.938402, -0.284611, 0.269598, -0.919953, 0.04142, -0.149024, -0.987966, 0.12454, -0.702485, -0.700717, 0.0027959, -0.188166, -0.982133 };
const unsigned int nor_size= 18;
when I called this array from my main file as shown here:
extern float nor[nor_size];
I got some error: cannot use nor_size as a const
how to solve this?
thanks

how to solve this?
The best would be for the generator of the nor.c file to also generate a corresponding nor.h file
#ifndef NOR_INCLUDE_GUARD
#define NOR_INCLUDE_GUARD
extern const float nor[18];
extern const unsigned int nor_size;
#endif
main.c uses that .h file
// Rather than
// extern float nor[nor_size];
// Include
#include "nor.h"
Also recommend the generator of the nor.c fil to append an f suffix to each constant.

In your main.c remove extern float nor[nor_size]; then add
extern const float nor[];
extern const unsigned int nor_size;
and use them as appropriate. Indeed, nor_size might then be loaded (in processor registers at the machine code level) several times.
For more, read this C reference, and later some C standard like n1570 or better.
If you are allowed to compile all your C (both handwritten and generated) code with some recent GCC compiler (or cross-compiler), invoke it at least with -Wall -Wextra -g options.
don't forget to read the documentation of your C compiler!
You also need to understand what is your linker, and read its documentation. Maybe it could be GNU binutils.
You could use some static source code analyzer, like Clang static analyzer, or Frama-C, or Bismon. FYI, Bismon has 24604 lines of generated C code, and the Bigloo compiler has a lot of them too.
for Frama-C or Bismon, contact me by email to basile.starynkevitch#cea.fr and mention the URL of your question
Read also a good C programming book, like Modern C
In 2021, you could be interested by the DECODER project. It is strongly related to your question.
An interesting book describing a software which generates all the half-million lines of code of its C source (available here) is Pitrat's Artificial Beings: the Conscience of a Conscious Machine (ISBN 978-1848211018). You could enjoy reading that book.
See also this answer about generating C code.
You could also be interested by GNU bison. It is a free software parser generator, mostly written in C, and generates C code. My recommendation is to download its source code and take inspiration from it.
By experience, when you are generating C code, it is easier to improve the generator (so that the generated C code compiles cleanly without warnings) that to change the generated C code. But do document well your C code generator. Read about partial evaluation techniques.

Related

paste operator in macros

I found the following snippet of code .
#define f(g,g2) g##g2
main() {
int var12=100;
printf("%d",f(var,12));
}
I understand that this will translate f(var,12) into var12 .
My question is in the macro definition, why didn't they just write the following :
#define f(g,g2) gg2
why do we need ## to concatenate text, rather than concatenate it ourselves ?
If one writes gg2 the preprocessor will perceive that as a single token. The preprocessor cannot understand that that is the concatenation of g and g2.
#define f(g,g2) g##g2
My opinion is that this is poor unreadable code. It needs at least a comment (giving some motivation, explanation, etc...), and a short name like f is meaningless.
My question is in the macro definition, why didn't they just write the following :
#define f(g,g2) gg2
With such a macro definition, f(x,y) would still be expanded to the token gg2, even if the author wanted the expansion to be xy
Please take time to read e.g. the documentation of GNU cpp (and of your compiler, perhaps GCC) and later some C standard like n1570 or better.
Consider also designing your software by (in some cases) generating C code (inspired by GNU bison, or GNU m4, or GPP). Your build machinery (e.g. your Makefile for GNU make) would process that as you want. In some cases (e.g. programs running for hours of CPU time), you might consider doing some partial evaluation and generating specialized code at runtime (for example, with libgccjit or GNU lightning). Pitrat's book on Artificial Beings, the conscience of a conscious machine explains and arguments that idea in an entire book.
Don't forget to enable all warnings and debug info in your compiler (e.g. with GCC use gcc -Wall -Wextra -g) and learn to use a debugger (like GNU gdb).
On Linux systems I sometimes like to generate some (more or less temporary) C code at runtime (from some kind of abstract syntax tree), then compile that code as a plugin, and dlopen(3) that plugin then dlsym(3) inside it. For a stupid example, see my manydl.c program (to demonstrate that you can generate hundreds of thousands of C files and plugins in the same program). For serious examples, read books.
You might also read books about Common Lisp or about Rust; both have a much richer macro system than C provides.

About C compilation process and the linking of libraries

Are C libraries linked with object code or first with source code so only later with object code? I mean, look at the image found at Cardiff School of Computer Science & Informatics's website
:
It's "strange" that after generating object-code the libraries are being linked. I mean, we use the source code while putting the includes!
So.. How this actually works? Thanks!
That diagram is correct.
When you #include a header, it essentially copies that header into your file. A header is a list of types and function declarations and constants, etc., but doesn't contain any actual code (C++ and inline functions notwithstanding).
Let's have an example: library.h
int foo(int num);
library.c
int foo(int num)
{
return num * 2;
}
yourcode.c
#include <stdio.h>
#include "library.h"
int main(void)
{
printf("%d\n", foo(100));
return 0;
}
When you #include library.h, you get the declaration of foo(). The compiler, at this point, knows nothing else about foo() or what it does. The compiler can freely insert calls to foo() despite this. The linker, seeing a call to foo() in youcode.c, and seeing the code in library.c, knows that any calls to foo() should go to that code.
In other words, the compiler tells the linker what function to call, and the linker (given all the object code) knows where that function actually is.
(Thanks to Fiddling Bits for corrections.)
Includes from libraries normally contain only library interface - so in the simplest case the .h file provided with the library contains function declaration, and the compiled function is in the library file. So you compile the sources with provided library functions declarations from library headers, and then linker adds the compiler library functions to your executable.
It might be instructive to look at what each piece in the tool-chain does, so using the boxes in your image.
pre-processor
This is really a text-editor doing a bunch of substitutions (ok, really really oversimplified). Some of the things that the pre-processor does is:
performs simple textual based substitution on #defines. So if we have #define PI 3.1415 in our file and then later on we have a line such as angle = angle * PI / 180; the pre=processor will convert this line into angle = angle * 3.1414 / 180;
anytime we encounter an #include, we can imagine that the pre-processor goes and gets the entire contents of that file and pastes the contents on the file on to where the #include is. (and then we go back and perform the substitutions.
we can also pass options to the compiler with the #pragma directive.
Finally, we can see the results of running the pre-processor by using the -E option to gcc.
compiler
The output of the pre-processor is still text, and it not contains everything that the compiler needs to be able to process the file. Now the compiler does a lot of things (and I normally break the box up when I describe this process). The compiler will process the text, do a lexical analysis of it, pass it to the parser that verifies that the program satisfies the grammar of the language, output an intermediate representation of the language, perform optimization and produce assembly code.
We can see the results of running up to the assembler by using the -s option to gcc.
assembler
The output of the compiler is an assembly listing, which is then passed to an assembler (most commonly `gas' (GNU assembler) on Linux), that converts the assembly code into machine code. In addition, on task of the assembler is to build a list of undefined referenced (i.e. a library function of a function that you wrote that is implemented in another source file.)
We can see the results of getting the output of the assembler by using the -c option to gcc.
linker
The input to the linker will be the output from the assembler (typically called object files and use an extention 'o'), as well as various libraries. Conceptually, the linker is responsible for hooking everything together, including fixing up the calls to functions that are found in libraries. Normally, the program that performs the linking in Linux is ld, and we can see the results of linking just by running gcc without any special command line options.
I have simplified the discussion of the linker, I hope I gave you a flavor of what the linker does.
The only issue that I have with the image you referenced, is that I would have move the phase "Object Code" to immediately below the assembler box, and at the same time I would move the arrow labeled "Libraries" down. I feel that this would indicate that the object code from the assembler is combined with libraries and these are combined by the linker to make an executable.
The Compilation Process of C with

Get preprocessed C code altogether with library implementation

I use *nix/gcc. I am beginner in C so this may be an easy question. Let's say I have a file main.c with the following content:
#include<stdio.h>
int main(int argc, char *argv[])
{
printf("Hello World.\n");
return 0;
}
Now what I want to get is one file which contains all code after preprocessing and all library implementation code (for inspection purpose). Now, if I run
gcc -E main.c >> full.c
I do get bunch of code, but there are only data types and function prototypes. Is it possible somehow to also get implementation of all functions, so that I can see whole code in one place.
Thanks.
The C Preprocessor just does text manipulation. In this case what it will do is to generate an output file that will contain the contents of the include file stdio.h along with the couple of lines of your main program.
It will not contain the stdio.h function implementations as that source is in some other files which are not provided in source code format with gcc.
So if you want the implementation you will need to find the gcc Standard C library source code which I expect is on the web some place.
However if you want to understand the Standard C library you should start with Plaughers books on the Standard C library or something similar which provides implementation as well as annotations and notes about what is done and why.

What is the purpose of using #ifdef _LANGUAGE_C in VisualDSP++?

I am modifying some code for a Blackfin processor using VisualDSP++ v. 5.0. I have noticed that all of the header files in this project utilize the following convention:
#ifdef _LANGUAGE_C
/* All of the code associated with this header file. */
#endif
After searching through the documentation for this compiler I found the following:
_LANGUAGE_C - Always defined as 1.
So my question is two-fold.
What is the purpose of using #ifdef _LANGUAGE_C?
Wouldn't this just keep your code from running on a different compiler that may not have a macro defined for _LANGUAGE_C?
You have to look at how it is used in context, however I believe that in this case it is used in headers that are used in both C code and assembler where the assembler code utilises the C pre-processor. It allows C headers to be included in assembler code, and have the preprocessor remove the C code specific elements.
For example it is useful in assembler code to have the same #define ... constant macro values as the C code to avoid duplication and inconsistency, but a struct definition or function prototype for example would be meaningless.
I would expect perhaps:#if defined(_LANGUAGE_C) || defined(_LANGUAGE_C_PLUS_PLUS), but if the documentation says that it is always defined, perhaps it is defined for both C and C++ compilation in your case.
To answer your compound question, the answer is yes, for the most part. This is part of some pre processor directives that allow you to build for different environments using the same code. If you look through the windows driver kit for example, you see this convention utilized all over the place to ensure that the most efficient code is build depending on the target environment and compiler. I hope this is helpful. The could have potentially added code in there after the #ifdef with another for _LANGUAGE_CPP and put C++ specific code in there etc etc.
It is called a compilation constant, such compilation constant must be added to your build environment, you should check your build environment. It is to tell the compiler that the code it going to compile are to compiled with C specific checks and will generate outfut file(hex or bin) depending on that.

How to compile assembly language in c

I am looking at lots of assembly language code that is compiled along with c. They are using simple #define assembly without any headers in boot.s code. How does this work ?
Typically .s files are processed by an assembler. Without knowing any other details, there's nothing more to say. .s file goes in, .o file comes out.
Many assemblers provide some kind of include directive to allow use of headers, which would also be in assembly language.
Ah, the code you linked is for use by the GNU as assembler. If you're on Linux or Mac, do man as to learn about it. If you're on Windows, install MinGW or Cygwin.
Compilers can frequently include in-line assembly, but I believe it is compiler specific.
I don't remember the precise details, but I think its something like:
void myFunc(void)
{
int myNum; /* plain old C */
__asm /* Assembly */
{
mov ax,bx;
xor cx,cx;
}
myNum = 5; /* more C */
}
Research your specific compiler for details.
The link you post in your comment is an assembly language source file that is meant to be first run through a c-preprocessor. It's just a programming convenience, but lots of assembly language compilers support similar constructs anyway, so I'm not sure why they went the c-preprocessor route.
If you have "main proc" inside of your code, you are using x86 architecture and your file ends with .asm you con use for compilation:
tasm fileName.asm
In result you will get your fileName.obj file. After that you need to link it and for
that you can use tlink filename.obj
To run, just enter the filename.exe on the command line
If you need to link more than one file use tlink filename1.obj filename2.obj and so on
during the compilation and linking is not necessary to specify the file extension like .obj or .asm. Using just filename should be fine.

Resources