How to print a Vector2D in unrealscript - unrealscript

I have this function:
function AddImpulse(Vector2D impulse)
{
`log("ADD IMPULSE: " $ impulse);
}
The trouble is that I get the error "Right type is incompatible with '$'. It seems that, although the built-in vector class will automatically coerce to a string, the Vector2D class is just a built-in struct without any operator overloading or automatic conversion.
I wrote an operator overload that help the situation, but unless I put the declaration of the overload in the object class (which I'm lead to believe shouldn't be done) I have to declare it in every class that may use it:
static final operator(40) string $ (string A, Vector2D B)
{
return A $ string(B.x) $ ", " $ string(B.y);
}
Is there a way this can be done generically so that I don't need to do this every time:
`log("ADD IMPULSE: " $ impulse.x $ "," $ impulse.Y);
Although that is not bad in the case of a Vector2D, this will become cumbersome with larger structures or classes.

Your options for generic programming in UnrealScript are limited, unfortunately. One option may be to put your operator overload in an include file and include it in each class that needs it using the `include macro.
If that doesn't work, another option may be to use a macro to invoke a static function in a special class for handling struct to string conversions.
First create a Globals.uci file in your code package's root folder. Globals.uci is a special file which is automatically included by the compiler in all UncrealScript files in the package it is associated with. If your package is called MyPackage, Globals.uci would go in Development/Src/MyPackage/Globals.uci. It should be next to the Classes folder for your package.
Put your macro in Globals.uci:
`define toString(type,name) class'MyStructConversions'.static.`{type}ToString(`{name},"`{name}")
Put your conversion function in MyStructConversions.uc:
class MyStructConversions;
static function string Vector2DToString (const out Vector2D A, string varname)
{
return varname $ ": (" $ A.X $ ", " $ A.Y $ ")";
}
Now when you call `toString(Vector2D, impulse) from anywhere in your package the macro will be replaced at compile time with an invocation to your Vector2DToString function. You can then support more struct types by adding the appropriate definitions to MyStructConversions.uc, and the toString macro will work seamlessly with them.
The documentation on the UnrealScript preprocessor has more information on `include and other macros. Check out Globals.uci in Development/Src/Core for some useful examples as well.

Related

C Makefile commands

I was trying to build a C project which has a rather unfamiliar way to define namespaces, eg. in file root.h
#define eval CRYPTO_NAMESPACE(eval)
And in the Makefile the following appears (rule for make all):
gcc -O3 -g -march=native -mtune=native -Wall -I. -Isubroutines -DKAT -DKATNUM='cat KATNUM' "-DCRYPTO_NAMESPACE(x)=x" "-D_CRYPTO_NAMESPACE(x)=_##x" -o kat nist/kat_kem.c nist/rng.c benes.c bm.c controlbits.c decrypt.c encrypt.c gf.c operations.c pk_gen.c root.c sk_gen.c synd.c transpose.c util.c -I${PWD}/subroutines -L${PWD}/libs/ -lXKCP -lcrypto -ldl
What do these options do:
"-DCRYPTO_NAMESPACE(x)=x" "-D_CRYPTO_NAMESPACE(x)=_##x"
I know that -DXXX=YYY is the same as #define XXX YYY. Now, why is it in double-quotes? Why it looks like a macro (may be it is)? Lastly, what does _##x mean?
The macro in the header:
#define eval CRYPTO_NAMESPACE(eval)
Replaces every token eval with CRYPTO_NAMESPACE(eval). So if the code contains
void eval(char *expr) {
...
the preprocessor output - without any other definition - would be
void CRYPTO_NAMESPACE(eval)(char *expr) {
...
The -D parameters effectively add two more definitions:
#define DCRYPTO_NAMESPACE(x) x
#define _CRYPTO_NAMESPACE(x) _##x
In our example, the first define causes the normal result to be re-written one more time:
void eval(char *expr) {
...
so we're back where we started. A different definition could be used to change the compiled name of the function. This definition makes the header definition a no-op.
The second macro uses the token concatenation operator ##. It adds a prefix underscore _ to the macro argument. E.g. if the code contained something like:
void _CRYPTO_NAMESPACE(foo)(int x) {
then the result is
void _foo(int x) {
At a higher level, these macros allow names of things (in the first case anything named eval and in the second, any name at all) to be transformed uniformly throughout the program. This is a fairly standard workaround for name collisions in big C programs. If you have two source code bases that have both defined the same public function name, macros like this can be used to add a prefix or suffix that changes one or both names in the compiled code without modifying either original code. This is an important capability for long-term configuration management where manually editing externally furnished code bases isn't a serious option.
A wild guess is that this treatment is given to eval because the likelihood of some other chunk of C also defining a function named eval is extremely high.

Using macros to generalise code for function calls

I'm writing C code which requires me to use multiple function calls of the same definition which differ only by single characters. Is there a way I can make a macro function which takes say a number and can insert these calls into my code for me where I call the macro given I know the numbers at compile time:
i.e.
#define call_pin_macro(X)
enable_pin#X();
do_thing_pin#X();
do_other_thing_pin#X();
.
.
void pin_function(void){
call_pin_macro(1);
call_pin_macro(2);
call_pin_macro(3);
}
Instead of:
void pin_function(void){
enable_pin1();
do_thing_pin1();
do_other_thing_pin1();
enable_pin2();
do_thing_pin2();
do_other_thing_pin2();
enable_pin3();
do_thing_pin3();
do_other_thing_pin3();
}
As a note I have looked at stringification (Hence the included #X's) in gcc however I cannot get the above code to compile which I get an error "error: '#' is not followed by a macro parameter". And it thus it seems this isn't exactly the functionality I am after. Thanks in advance.
In gcc you can do it like this:
#define call_pin_macro(X) \
enable_pin##X(); \
do_thing_pin##X(); \
do_other_thing_pin##X();
The double hash is the macro concatenation operator. You don't want to use stringify because that will put quotes around it.
The backslashes allow you to continue the macro over several lines.

List all functions declared in header but missing in the source file?

Question
Are there some linters/statical analyzers that warn/error on functions, that are declared in the header file but not implemented in the corresponding source file?
Lets say we have the following header (guard omitted):
/* example.h */
int doSomething(int i);
double doSomethingElse(double d);
And the following source:
/* example.c */
#require "example.h"
int doSomething(int i) {
return i + 1;
}
So is there some tool, that can tell me that doSomethingElse() is missing in example.c?
Why asking?
In an exercise we got some headerfiles with a fully fletched interface, and partially prepared sourcefiles, with some functions beeing fully provided, some functions beeing partially provided, and some missing.
For actually running and compiling this programm it was enough to complete the partially provided functions, but still there is some discrepancy between the defined interface in the header and the now provided functions in the source file.
I could go through all header/source pairs by hand and implement the missing funtions, but it would be nice to have some autogenerated todolist.
I'd just do it with grep etc.:
grep ');' foo.h | tr -d ';' | while read decl
do
if ! grep -q "$decl" foo.c
then
echo "not found: $decl"
fi
done
No, this isn't perfect, but it might work if your use case is as simple as you've outlined.

unused functions detection utility for c

I am trying to measure my code coverage utilization on a C project consist of several libraries, and main program.
Is there a utility that can help me find which function I dont use from both libraries and main program.
I want to build list of functions (public functions) that are not used by my main program, in order to ignore them in my code coverage report.
If you are using gcc you compile your code with option:
-Wunused-function
Warn whenever a static function is declared but not defined or a non-inline static function is unused. This warning is enabled by -Wall.
cflow can create a call graph for the program, but it doesn't work well with pointers to functions in some cases.
for eaxample:
#include <stdio.h>
static int f1(){
return 1;
}
int (*p_f1)() = f1;
int main() {
p_f1();
return 0;
}
There are coverage tools available for free - for example "gcov" that runs on go with the gcc tool suite. However, Code Coverage only tells you which functions get hit by your testing (or whatever you do to excercise the code), so for example
ptr = malloc(...);
if (!ptr)
{
allocation_failed(__FILE__, __LINE__);
}
would only show that allocation_failed is called if you are also using some tool that makes your allocations fail from time to time.
I'm not aware of a tool that will show you what functions are not used across larger systems (with multiple libraries, etc). I expect you could make something by using the output of "nm" and a bit of "pulling things in". It won't cover foo and bar as unusued in this case:
unit1.c:
extern int foo(void);
int bar()
{
return foo();
}
unit2.c:
int foo(void)
{
return 42;
}
int baz(void)
{
return bar();
}
and then baz isn't used anywhere. But if you remove baz, it will show that bar is not called, and then you can remove foo after that...
Edit: Crazy idea time - how about taking every C file in the project and just concatenating the whole thing into a a single .C file, then add static at the beginning of every function, and compiling with -Wunused-functon - I'm sure there will be some "interesting" effects from this if your code isn't extremely well written, but it may be worth a try [it would be fairly easy to do this in a Linux system, something like find . -name "*.c" -print | xargs cat {} > giantsource.c - you then need a little bit of sed or something to label all functions static, which I'm not quite sure how you'd go about doing - it depends very much on the formatting of your code.
You may want to have a look at this:
http://www.gedanken.demon.co.uk/cxref/
I haven't used it, but any decent cross referencing tool should be able to identify anything that is "not used" as not having any references. Of course, you'll probably still have to run over the code severa times to weed out the functions that are used by functions that aren't being called, etc.
cflow has an option to build a cross-reference table: --xref
The format of the output is described by GNU cflow: Cross-Reference
GNU cflow is also able to produce cross-reference listings. This mode is enabled by --xref (-x) command line option. Cross-reference output lists each symbol occurrence on a separate line. Each line shows the identifier and the source location where it appears. If this location is where the symbol is defined, it is additionally marked with an asterisk and followed by the definition. For example, here is a fragment of a cross-reference output for d.c program:
printdir * d.c:42 void printdir (int level,char *name)
printdir d.c:74
printdir d.c:102
It shows that the function printdir is defined in line 42 and referenced twice, in lines 74 and 102.
To detect unused functions, search the line with a star not followed by a line with the same prefix. The following GNU Awk code print the unused functions:
{
if( $2 == "*" ) {
if( f ) {
print f
}
f = $1
}
else {
f = ""
}
}
The command may be:
cflow -x src/*.c src-gen/*.c | awk -f find-unused-functions.awk

How to store a version number in a static library?

How can I store a version number in a static library (file.a) and later check for its version in Linux?
P.S. I need possibility to check version of file any time without any special executable using only by shell utilities.
In addition to providing a static string as mentioned by Puppe, it is common practice to provide a macro to retrieve the version check for compatibility. For example, you could have the following macros (declared in a header file to be used with your library):
#define MYLIB_MAJOR_VERSION 1
#define MYLIB_MINOR_VERSION 2
#define MYLIB_REVISION 3
#define MYLIB_VERSION "1.2.3"
#define MYLIB_VERSION_CHECK(maj, min) ((maj==MYLIB_MAJOR_VERSION) && (min<=MYLIB_MINOR_VERSION))
Notice with the MYLIB_CHECK_VERSION macro, I'm assuming you want a specific major rev and a minor rev greater than or equal to your desired version. Change as required for your application.
Then use it from a calling application, something like:
if (! MYLIB_VERSION_CHECK(1, 2)) {
fprintf(stderr, "ERROR: incompatible library version\n");
exit(-1);
}
This approach will cause the version information to come from the included header file. Additionally, it will be optimized at compile time for the calling application. With a little more work, you can extract it from the library itself. Read on...
You can also use this information to create a static string stored inside your library, as mentioned by Puppe. Place something like this inside your library:
struct {
const char* string;
const unsigned major;
const unsigned minor;
const unsigned revision;
} mylib_version = {
MYLIB_VERSION, MYLIB_MAJOR_VERSION, MYLIB_MINOR_VERSION, MYLIB_REVISION
};
This will create a struct called mylib_version in your library. You can use this to do further verifications by creating functions inside your library and accessing those from a calling application, etc.
Maybe you could create a string with the version like this:
char* library_version = { "Version: 1.3.6" };
and to be able to check it from the shell just use:
strings library.a | grep Version | cut -d " " -f 2
Creating a new answer based on your edit... Just to avoid confusion :)
If you are looking for a non-code way to solve the problem, you could try this. It's (yet again) an alternative to the strings approach defined by Puppe.
Maybe you could just touch a file called version_1.2.3 and add it to the archive. Then, you could determine the version by looking for the version file using the ar command:
ar t libmylib.a | grep 'version_' | sed -e 's/^version_//'
I'm not sure if that will get you what you need, but there is no standard method for embedding metadata like this in an archive. Maybe you'll find other information you want to store in this "metafile" for the archive.
If you are using gcc, you can use the #ident directive
#ident "Foo Version 1.2.3.4"
void foo(void){ /* foo code here */ }
To get the version just use one of the following:
strings -a foo.o | grep "Foo Version"
strings -a foo.a | grep "Foo Version"
strings -a foo.so | grep "Foo Version"
This will allow you to compile the version into the library with the capability of later stripping it out using strip -R .comment your_file or completely omit it by passing -fno-ident (This will also omit the compiler version comments from the compiled objects)
Several times man 1 ident has been mentioned, so here are details about using that method.
ident is a command that comes with the RCS (Revision Control System), but might also be available if you are using CVS (Concurrent Versions System), or Subversion.
You would use it like this (cloned from the man page):
#include <stdio.h>
static char const rcsid[] =
"$Id: f.c,v 5.4 1993/11/09 17:40:15 eggert Exp $";
int main() { return printf("%s\n", rcsid) == EOF; }
and f.c is compiled into f.o, then the command
ident f.c f.o
will output
f.c:
$Id: f.c,v 5.4 1993/11/09 17:40:15 eggert Exp $
f.o:
$Id: f.c,v 5.4 1993/11/09 17:40:15 eggert Exp $
If your f.o were added to a static library f.a then ident f.a should show a similar output. If you have several similarly built [a-z].o in your az.a you should find all their strings in the az.a file.
CAVEAT: Just because they are in the .a file doesn't mean they will be included in your program file. Unless the program references them the linker sees no need to include them. So you usually have to have a method in each module to return the string, and the app needs to call that method. There are ways to convince most linkers that it is a required symbol without actually referencing it, but it depends on the linker, and is beyond the scope of this answer.
If instead you are familiar with the SCCS (Source Code Control System) then you would use man 1 what instead, and it would look like this (done with macros to show the flexibility available):
#include <stdio.h>
#define VERSION_STR "5.4"
#define CONFIG "EXP"
#define AUTHOR "eggert"
static char const sccsid[] =
"#(#) " CONFIG " v " VERSION_STR " " __DATE__ " " __TIME__ " " AUTHOR;
int main() { return printf("%s\n", sccsid) == EOF; }
and f.c is compiled into f.o, then the command
what f.c f.o
will output
f.c:
#(#) EXP v 5.4 1993/11/09 17:40:15 eggert
f.o:
#(#) EXP v 5.4 1993/11/09 17:40:15 eggert
PS: both ident and what are commands that come with specific centralized source control systems. If you are using a distributed source control system (like git) the entire concept may not make sense. For some ideas using git see this thread: Moving from CVS to git: $Id:$ equivalent? though the hash isn't the same as a version number. :)

Resources