How to compile VTProlog from source code? - c

I am a student in Computer Science, and I am learning about logic programming with Prolog.
I have found an interesting Prolog interpreter, VTProlog (https://github.com/Johnicholas/Hello-Github/blob/master/prolog-in-hundreds-of-loc/vtprolog-in-c/vtprolog.pas).
To know more about Prolog, I am trying to compile their source code. And, I got success with Turbo Pascal 7.0, but failed with Free Pascal 2.6.4.
vtprolog.pas(1195,8) Error: Identifier not found "l"
vtprolog.pas(1198,30) Error: Identifier not found "l"
vtprolog.pas(1199,16) Error: Identifier not found "l"
vtprolog.pas(1203,34) Error: Identifier not found "l"
vtprolog.pas(1611) Fatal: There were 4 errors compiling module, stopping
vtprolog.pas(0) Fatal: Compilation aborted
Is there any way to compile it both with Turbo Pascal 7.0 (without any requirement) or Free Pascal 2.6.4 on Windows XP?

Without knowing too much about Pascal I think the problem is that part of line 1159:
Procedure print_functor (* l : node_ptr *) ;
has been commented out. Change that to:
Procedure print_functor (l : node_ptr) ;
and it should compile - at least it did when I tried with Ideone (using the Free Pascal Compiler). If the program will work as intended I can't say.

Did you put Free Pascal in strict Turbo Pascal Mode with -Mtp ? If I do it compiles, even with older 2.6.2.
D:\testing>fpc vtprolog.pp -Mtp
Free Pascal Compiler version 2.6.2 [2013/02/12] for i386
Copyright (c) 1993-2012 by Florian Klaempfl and others
Target OS: Win32 for i386
Compiling vtprolog.pp
vtprolog.pp(222,3) Note: Local variable "num" is assigned but never used
vtprolog.pp(310,3) Note: Local variable "s" not used
vtprolog.pp(1253,13) Note: Local variable "p" not used
vtprolog.pp(100,3) Note: Local variable "source_file" not used
vtprolog.pp(102,13) Note: Local variable "text_chars" is assigned but never used
vtprolog.pp(103,46) Warning: Variable "HeapPtr" read but nowhere assigned
Linking vtprolog.exe
1610 lines compiled, 0.3 sec , 43712 bytes code, 2204 bytes data
1 warning(s) issued
5 note(s) issued
For ideone, you can simulate the commandline parameter by adding {$mode tp} as first thing in the file (before the (*$V-... *) line ). I tested it with ideone, and it compiled.

Related

labels as values in clang

I'm trying to implement "labels as values" (https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html) in a c program using clang 3.7 in Visual Studio 2015.
As a toy example I had the following code which causes the compiler to crash (internal error "fatal error C1001: An internal error has occurred in the compiler.
1> (compiler file 'c:\agent\build\cache\git\vctools\vctools\compiler\utc\src\p2\main.c', line 246)
1> To work around this problem, try simplifying or changing the program near the locations listed above.").
const void *array_jump[] = {&&S1,&&S2,&&S3,&&S3,&&S4};
S1:
goto *array_jump[3];
S2:
return 2;
S3:
return 3;
S4:
return 4;
If I move the array declaration to after all of the labels it works, until I include the array_jump variable in any of the statements.
S1:
//comment out and add "return 1;" and it will compile fine
goto *array_jump[3];
S2:
return 2;
S3:
return 3;
S4:
return 4;
const void *array_jump[] = {&&S1,&&S2,&&S3,&&S3,&&S4};
Can anyone provide an example like the one above that should work? Is this a problem with clang or with the "codegen" aspect for Visual Studio?
I think this bug is relevant but I'm not sure:
https://connect.microsoft.com/VisualStudio/feedback/details/2103400/crash-in-clang-c2-with-address-of-label-extension
The examples you build should work, I've just verified it using Apple LLVM version 7.0.2 (clang-700.1.81).
The mentioned bug reports seem to report this very same issue, until it's fixed, you can't do anything aside from trying to not use the extension.
While GNU C has some great extensions, if you want to write portable c code, try to avoid using any GNU C extension.
What you've linked to is a gnu-specific extension to the language. If you're not using a gnu compiler (I don't believe clang is), then it won't necessarily work. The documentation says to check for definition of the __GNUC__ name in the processor. Try adding this...
#ifndef __GNUC__
#error Not a GNU compiler, does not include GNU specific extensions
#endif

GCC installed. Mathematica still won't compile to C

I'm running Mathematica 8 on a MacOSX, trying to compile even the simplest program to C. Anything having to do with C simply doesn't work in Mathematica. I have GCC 4.2 installed; I've even reinstalled it multiple times with XCode. Here's what I'm doing and the errors I'm getting:
First, I always evaluate the command
Needs["CCompilerDriver`"]
If I set the compilation target to C,
c = Compile[ {{x}}, x^2 + Sin[x^2], CompilationTarget -> "C"];
I get an error that reads: Compile::nogen : A library could not be created from the compiled function.
If I try to create a library,
demoFile = FileNameJoin[{$CCompilerDirectory,"SystemFiles","CSource","createDLL_demo.c"}];
lib = CreateLibrary[{demoFile},"testLibrary"]
I get an message $Failed. Wolfram says that this is because I don't have a C compiler installed. I find that hard to believe because when I run
CCompilers[]
It tells me that I've got GCC installed: {{"Name" -> "GCC",
"Compiler" -> CCompilerDriver'GCCCompiler`GCCCompiler,
"CompilerInstallation" -> "/usr/bin", "CompilerName" -> Automatic}}
What's more, terminal says I have GCC installed too!! Any help would be appreciated. I'd really like to compile Mathematica to C.
In this answer I'll collect some debugging steps for similar problems, for future reference. Feel free to edit/improve them.
If compiling to C code does not work from Mathematica 8,
Check that you have a supported C compiler installed and it works (the obvious).
Note that the compiler does not necessarily have to be in the PATH, at least on Windows/Visual Studio it doesn't.
Check that Mathematica recognizes the compiler
<< CCompilerDriver`
CCompilers[]
will list the compilers known to Mathematica.
Check what commands Mathematica executes to compile the generated C code:
Compiler`$CCompilerOptions = {"ShellCommandFunction" -> Print};
Compile[{{x}}, x^2, CompilationTarget -> "C"];
Note that with "ShellCommandFunction" -> Print the commands will not be executed, so you'll need to re-set Compiler`$CCompilerOptions to {} after this step is complete to allow command execution again.
Check the output/errors from the compiler:
Compiler`$CCompilerOptions = {"ShellOutputFunction" -> Print};
Compile[{{x}}, x^2, CompilationTarget -> "C"];
These last two steps will hopefully give you enough clues to proceed. With this information you can check if the correct library / include paths are passed to the compiler (in the case of gcc/icc, look at the -L option which specifies library paths and the -I option which specifies include paths). Then check if the required include and library files are present at those paths.
If you get Compile::nogen, you can see the compiler output by setting ShellOutputFunction->Print right in the Compile expression:
c = Compile[ {{x}}, x^2 + Sin[x^2],
CompilationTarget -> {"C", "ShellOutputFunction"->Print}];
In general, this is how you can pass options to the underlying CreateLibrary call, by changing CompilationTarget->"C" to CompilationTarget->{"C", options}. Setting Compiler`$CCompilerOptions works too, but this technique has the advantage of not setting a global variable.
It is a shame that the only error you are seeing is $Failed, that's not terribly helpful; I wonder if perhaps there are some file or directory permissions problems?
I'm running on linux not Mac so I am not sure if my setup is "close enough" or not. On my machine your Compile command succeeds and generates a file .Mathematica/ApplicationData/CCompilerDriver/BuildFolder/blackie-desktop-5077/compiledFunction1.so in my home directory. Is there any way you can find a .Mathematica directory associated with your userid, and see if it exists and is writeable by mathematica?
Also, you could check to see if "gcc" is or is not being accessed by checking the file access time of /usr/bin/gcc before and after your call to Compile. From an operating system shell you can do ls -lu /usr/bin/gcc or from Mathematica perhaps Import["!ls -lu /usr/bin/gcc", "Text"]

Linux C: Shell-like environment - for individual execution - of C commands? (C interpreter)

Sorry if the question is worded wrong - I don't know the right word for what I'm asking for! :)
Say, you have some simple C program like:
#include <stdio.h>
int main()
{
int a=2;
printf("Hello World %d\n", a);
return 0;
}
Typically, this would have to be saved in a file (say, hello.c); then we run gcc on the source file and obtain executable file - and if we compiled in debug information, then we can use gdb on the executable, to step through lines of code, and inspect variables.
What I would like to have, is basically some sort of a "C" shell - similar to the Python shell; in the sense that I can have a sequence of Python commands in a file (a script) - or I can just paste the same commands in the shell, and they will execute the same. In respect to the simple program above, this is what I'd like to be able to do (where C> represents the imagined prompt):
C> #include <stdio.h>
(stdio.h included)
C> int a=2;
C> printf("Hello World %d\n", a);
Hello World 2
C>
In other words, I'd like to be able to execute individual C commands interactively (I'm guessing this would represent on-the-fly compilation of sorts?). Initially I was misled by the name of the C shell (csh) - but I don't think it will be able to execute C commands on the fly.
So, first and foremost, I'd like to know if it is possible somehow to persuade, say, gdb to perform in this manner? If not, is there anything else that would allow me to do something similar (some special shell, maybe)?
As for the context - I have some code where I have problems troubleshooting pointers between structs and such; here the way gdb can printout structs works very well - however, to isolate the problem, I have to make new source files, paste in data, compile and debug all over again. In this case, I'd much rather have the possibility to paste several structs (and their initialization commands) in some sort of a shell - and then, inspect using printf (or even better, something akin to gdb's print) typed directly on the shell.
Just for the record - I'm not really persuaded something like this really exists; but I thought I'd ask anyways :)
Thanks in advance for any answers,
Cheers!
EDIT: I was a bit busy, so haven't had time to review all answers yet for accept (sorry :) ); just wanted to add a little comment re:"interpreted vs. machine code"; or as mentioned by #doron:
The problem with running C /C++ source interactively is that
the compiler is not able to perform line by line interpretation of the code.
I am fully aware of this - but let's imagine a command line application (could even be an interpreted one), that gives you a prompt with a command line interface. At start, let's assume this application generates this simple "text file" in memory:
##HEADER##
int main()
{
##MAIN##
return 0;
}
Then, the application simply waits for a text to be entered at the prompt, and ENTER to be pressed; and upon a new line:
The application checks:
if the line starts with #define or #include, then it is added below the ##HEADER## - but above the int main() line - in the temp file
anything else, goes below ##MAIN## line - but above return 0; line - in the temp file
the temp file is stripped of ##HEADER## and ##MAIN## lines, and saved to disk as temp.c
gcc is called to compile temp.c and generate temp.out executable
if fail, notify user, exit
gdb is called to run the temp.out executable, with a breakpoint set at the return 0; line
if fail, notify user, exit
execution is returned to the prompt; the next commands the user enters, are in fact passed to gdb (so the user can use commands like p variable to inspect) - until the user presses, say, Ctrl+1 to exit gdb
Ctrl+1 - gdb exits, control is returned to our application - which waits for the next code line all over again.. etc
(subsequent code line entries are kept in the temp file - placed below the last entry from the same category)
Obviously, I wouldn't expect to be able to paste the entire linux kernel code into an application like this, and expect it to work :) However, I would expect to be able to paste in a couple of structs, and to inspect the results of statements like, say:
char dat = (char) (*(int16_t*)(my->structure->pdata) >> 32 & 0xFF) ^ 0x88;
... so I'm sure in what is the proper syntax to use (which is usually what I mess up with) - without the overhead of rebuilding and debugging the entire software, just to figure out whether I should have moved a right parenthesis before or after the asterisk sign (in the cases when such an action doesn't raise a compilation error, of course).
Now, I'm not sure of the entire scope of problems that can arise from a simplistic application architecture as above. But, it's an example, that simply points that something like a "C shell" (for relatively simple sessions/programs) would be conceptually doable, by also using gcc and gdb - without any serious clashes with the, otherwise, strict distinction between 'machine code' and 'interpreted' languages.
There are C interpreters.
Look for Ch or CINT.
Edit: found a new (untested) thing that appears to be what the OP wants
c-repl
Or just use it [...] like driving a Ferarri on city streets.
Tiny C Compiler
[... many features, including]
C script supported : just add '#!/usr/local/bin/tcc -run' at the first line of your C source, and execute it directly from the command line.
When your CPU runs a computer program, it runs something called machine code. This is a series of binary instructions that are specific to the CPU that you are using. Since machine code is quite hard to hand code, people invented higher level languages like C and C++. Unfortunately the CPU only understands machine code. So what happens is that we run a compiler that converts the high-level source language into machine code. Computer languages in this class are compiled language like C and C++. These languages are said to run natively since the generated machine code is run by the CPU without any further interpretation.
Now certain languages like Python, Bash and Perl do not need to be compiled beforehand and are rather interpreted. This means that the source file is read line by line by the interpreter and the correct task for the line is performed. This gives you the ability run stuff in an interactive shell as we see in Python.
The problem with running C /C++ source interactively is that the compiler is not able to perform line by line interpretation of the code. It is designed solely to generate corresponding machine code and therefore cannot run your C / C++ source interactively.
#buddhabrot and #pmg - thank you for your answers!
For the benefit of n00bery, here is a summary of the answers (as I couldn't immediately grasp what is going on): what I needed (in OP) is handled by what is called a "C Interpreter" (not a 'C shell'), of which the following were suggested:
CINT | ROOT - Ubuntu: install as sudo apt-get install root-system-bin (5.18.00-2.3ubuntu4 + 115MB of additional disk space)
c-repl (c-repl README)- Ubuntu: install as sudo apt-get install c-repl (c-repl_0.0.20071223-1_i386.deb + 106kB of additional disk space)
Ch standard edition - standard edition is freeware for windows/Unix
For c-repl - there is a quick tutorial on c-repl homepage as an example session; but here is how the same commands behave on my Ubuntu Lucid system, with the repository version (edit: see Where can I find c-repl documentation? for a better example):
$ c-repl
> int x = 3
> ++x
> .p x
unknown command: p
> printf("%d %p\n", x, &x)
4 0xbbd014
> .t fprintf
repl is ok
> #include <unistd.h>
<stdin>:1:22: warning: extra tokens at end of #include directive
> getp
p getp
No symbol "getp" in current context.
> printf("%d\n", getpid())
10284
> [Ctrl+C]
/usr/bin/c-repl:185:in `readline': Interrupt
from /usr/bin/c-repl:185:in `input_loop'
from /usr/bin/c-repl:184:in `loop'
from /usr/bin/c-repl:184:in `input_loop'
from /usr/bin/c-repl:203
Apparently, it would be best to build c-repl from latest source.
For cint it was a bit difficult to find something relateed to it directly (the webpage refers to ROOT Tutorials instead), but then I found "Le Huy: Using CINT - C/C++ Interpreter - Basic Commands"; and here is an example session from my system:
(Note: if cint is not available on your distribution's package root-system-bin, try root instead.)
$ cint
cint : C/C++ interpreter (mailing list 'cint#root.cern.ch')
Copyright(c) : 1995~2005 Masaharu Goto (gotom#hanno.jp)
revision : 5.16.29, Jan 08, 2008 by M.Goto
No main() function found in given source file. Interactive interface started.
'?':help, '.q':quit, 'statement','{statements;}' or '.p [expr]' to evaluate
cint> L iostream
Error: Symbol Liostream is not defined in current scope (tmpfile):1:
*** Interpreter error recovered ***
cint> {#include <iostream>}
cint> files
Error: Symbol files is not defined in current scope (tmpfile):1:
*** Interpreter error recovered ***
cint> {int x=3;}
cint> {++x}
Syntax Error: ++x Maybe missing ';' (tmpfile):2:
*** Interpreter error recovered ***
cint> {++x;}
(int)4
cint> .p x
(int)4
cint> printf("%d %p\n", x, &x)
4 0x8d57720
(const int)12
cint> printf("%d\n", getpid())
Error: Function getpid() is not defined in current scope (tmpfile):1:
*** Interpreter error recovered ***
cint> {#include <unistd.h>}
cint> printf("%d\n", getpid())
10535
(const int)6
cint> .q
Bye... (try 'qqq' if still running)
In any case, that is exactly what I needed: ability to load headers, add variables, and inspect the memory they will take! Thanks again, everyone - Cheers!
Python and c belongs to different kinds of language. Python is interpreted line by line when running, but c should compile, link and generate code to run.

Is there a tool to make a c compiler in win7 with yacc and lex?

The only tool is found is this Parser Generator:
Operating System: Windows 95 / 98 / ME / NT / 2000 / XP
But seems it's not supporting win7,when I try to build for Visual C++(32 bit), got this error:
yyaslvar.c
C:\Program Files\Parser Generator 2\Cpp\Source\yyaslvar.c(35) : error C2099: initializer is not a constant
C:\Program Files\Parser Generator 2\Cpp\Source\yyaslvar.c(36) : error C2099: initializer is not a constant
C:\Program Files\Parser Generator 2\Cpp\Source\yyaslvar.c(37) : error C2099: initializer is not a constant
FILE YYFAR *YYNEAR YYDCDECL yyin = stdin;
FILE YYFAR *YYNEAR YYDCDECL yyout = stdout;
FILE YYFAR *YYNEAR YYDCDECL yylexererr = stderr;
I'm using Visual Studio 2010 Express.
I don't know about VS2010, but I've used this Win32 port of Lex/Yacc (Flex/Bison) on VS2005 without problems: http://userpages.monmouth.com/~wstreett/lex-yacc/lex-yacc.html
Also, your error is due to the fact that VC++ actually defines stdin, stdout etc. as macros which expand to function calls that return a FILE *. Clearly, these are not compile-time constants, which is what the error says.
Not so easy with windows. If you are ready to shell out some money , then you can use MKS lex and Yacc toolkit
http://www.mkssoftware.com/products/ly/
The problem has nothing to do with Win7 per se, and everything to do with (stricter!) ANSI C standards. The C compiler simply won't let you assign a macro (like "stdin" or "stdout") to a "non-automatic variable":
http://msdn.microsoft.com/en-us/library/t801az8a%28VS.80%29.aspx
Here's one workaround:
http://coding.derkeiler.com/Archive/C_CPP/comp.lang.c/2009-10/msg00982.html
stdin and stdout need not be constants, so you can't use them to
initalise static or global variables.
Do the assignments in an initialisation function instead.
Moreover, this link might get you pointed in the right direction:
http://msdn.microsoft.com/en-us/library/aa730877%28VS.80%29.aspx
'Hope that helps

zlib on z/OS USS

Im trying to compile z/lib on z/OS USS(thats right a mainframe). ive got gmake and the c89 compiler (which im assuming is c89 standards compliant) and USS is supposed to be POSIX compliant.
But zlib seems to be tripping up on
struct internal_state FAR *state; /* not visible by applications */
with the following error(s)
c89 -O3 -DUSE_MMAP -D_XOPEN_SOURCE_EXTENDED=1 -D_POSIX_SOURCE -c -o example.o example.c
ERROR CCN3277 ./zlib.h:92 Syntax error: possible missing ';' or ','?
ERROR CCN3007 ./zlib.h:92 "struct internal_state" is undefined.
ERROR CCN3166 ./zlib.h:103 Definition of function FAR requires parentheses.
ERROR CCN3276 ./zlib.h:103 Syntax error: possible missing '{'?
ERROR CCN3273 ./zlib.h:124 Missing type in declaration of gz_header.
ERROR CCN3166 ./zlib.h:126 Definition of function gz_header requires parentheses.
ERROR CCN3276 ./zlib.h:126 Syntax error: possible missing '{'?
WARNING CCN3137 ./zlib.h:1346 Declaration must declare at least one declarator, tag, or the members of an enumeration.
ERROR CCN3275 ./zlib.h:1350 Unexpected text z encountered.
ERROR CCN3282 ./zlib.h:1350 The type of the parameters must be specified in a prototype.
ERROR CCN3275 ./example.c:95 Unexpected text file encountered.
ERROR CCN3045 ./example.c:95 Undeclared identifier gzFile.
ERROR CCN3046 ./example.c:96 Syntax error.
ERROR CCN3045 ./example.c:98 Undeclared identifier file.
ERROR CCN3019 ./example.c:523 Expecting an array or a pointer to object type.
ERROR CCN3280 ./example.c:527 Function argument assignment between types "const char*" and "int" is not allowed.
CCN0793(I) Compilation failed for file ./example.c. Object file not created.
FSUM3065 The COMPILE step ended with return code 12.
FSUM3017 Could not compile example.c. Correct the errors and try again.
gmake: *** [example.o] Error 3
when i progressively take out the FAR * (i think its a far pointer but im really not that sure) the errors go away. But as this is a library, im not sure what other artifacts are going to be produced by removing this.
has anybody got any ideas?
any old mainframe heads out there?
it turns out there is a previous version of zlib that compiles on USS, version 1.1.4 or close to that. Its a back level, but i presume this works because it is before the implementation of the FAR pointer in the latest code. So atm i think ive got it to work.
thanks for all your help.
Regards
Mark.
FAR is not a C89 keyword, it is a Microsoft/Intelism and is probably #defined somewhere. If not, you need to define it as nothing:
#define FAR
However, this will probably only fix one of many problems. I would guess that the library uses some form of conditional compilation to handle things like FAR pointers - you need to read the docs to find which configuration is most suitabkle for your platform.
I'd use xlc instead of c89 since xlc is your system default compiler but you'll still probably have issues. I'd subscribe to the MVS-OE email list, the people on it are quite helpful. The link to info about the list appears to be down now so send email to
LISTSERV#VM.MARIST.EDU
with the message: INFO MVS-OE
FWIW, IBM provides a prebuilt version of zlib that includes support for the compression hardware (so-called zEDC) available on recent-vintage mainframes. See zlib for zEnterprise Data Compression

Resources