Run C or C++ file as a script - c++

So this is probably a long shot, but is there any way to run a C or C++ file as a script? I tried:
#!/usr/bin/gcc main.c -o main; ./main
int main(){ return 0; }
But it says:
./main.c:1:2: error: invalid preprocessing directive #!

Short answer:
//usr/bin/clang "$0" && exec ./a.out "$#"
int main(){
return 0;
}
The trick is that your text file must be both valid C/C++ code and shell script. Remember to exit from the shell script before the interpreter reaches the C/C++ code, or invoke exec magic.
Run with chmod +x main.c; ./main.c.
A shebang like #!/usr/bin/tcc -run isn't needed because unix-like systems will already execute the text file within the shell.
(adapted from this comment)
I used it in my C++ script:
//usr/bin/clang++ -O3 -std=c++11 "$0" && ./a.out; exit
#include <iostream>
int main() {
for (auto i: {1, 2, 3})
std::cout << i << std::endl;
return 0;
}
If your compilation line grows too much you can use the preprocessor (adapted from this answer) as this plain old C code shows:
#if 0
clang "$0" && ./a.out
rm -f ./a.out
exit
#endif
int main() {
return 0;
}
Of course you can cache the executable:
#if 0
EXEC=${0%.*}
test -x "$EXEC" || clang "$0" -o "$EXEC"
exec "$EXEC"
#endif
int main() {
return 0;
}
Now, for the truly eccentric Java developer:
/*/../bin/true
CLASS_NAME=$(basename "${0%.*}")
CLASS_PATH="$(dirname "$0")"
javac "$0" && java -cp "${CLASS_PATH}" ${CLASS_NAME}
rm -f "${CLASS_PATH}/${CLASS_NAME}.class"
exit
*/
class Main {
public static void main(String[] args) {
return;
}
}
D programmers simply put a shebang at the beginning of text file without breaking the syntax:
#!/usr/bin/rdmd
void main(){}
See:
https://unix.stackexchange.com/a/373229/23567
https://stackoverflow.com/a/12296348/199332

For C, you may have a look at tcc, the Tiny C Compiler. Running C code as a script is one of its possible uses.

$ cat /usr/local/bin/runc
#!/bin/bash
sed -n '2,$p' "$#" | gcc -o /tmp/a.out -x c++ - && /tmp/a.out
rm -f /tmp/a.out
$ cat main.c
#!/bin/bash /usr/local/bin/runc
#include <stdio.h>
int main() {
printf("hello world!\n");
return 0;
}
$ ./main.c
hello world!
The sed command takes the .c file and strips off the hash-bang line. 2,$p means print lines 2 to end of file; "$#" expands to the command-line arguments to the runc script, i.e. "main.c".
sed's output is piped to gcc. Passing - to gcc tells it to read from stdin, and when you do that you also have to specify the source language with -x since it has no file name to guess from.

Since the shebang line will be passed to the compiler, and # indicates a preprocessor directive, it will choke on a #!.
What you can do is embed the makefile in the .c file (as discussed in this xkcd thread)
#if 0
make $# -f - <<EOF
all: foo
foo.o:
cc -c -o foo.o -DFOO_C $0
bar.o:
cc -c -o bar.o -DBAR_C $0
foo: foo.o bar.o
cc -o foo foo.o bar.o
EOF
exit;
#endif
#ifdef FOO_C
#include <stdlib.h>
extern void bar();
int main(int argc, char* argv[]) {
bar();
return EXIT_SUCCESS;
}
#endif
#ifdef BAR_C
void bar() {
puts("bar!");
}
#endif
The #if 0 #endif pair surrounding the makefile ensure the preprocessor ignores that section of text, and the EOF marker marks where the make command should stop parsing input.

CINT:
CINT is an interpreter for C and C++
code. It is useful e.g. for situations
where rapid development is more
important than execution time. Using
an interpreter the compile and link
cycle is dramatically reduced
facilitating rapid development. CINT
makes C/C++ programming enjoyable even
for part-time programmers.

You might want to checkout ryanmjacobs/c which was designed for this in mind. It acts as a wrapper around your favorite compiler.
#!/usr/bin/c
#include <stdio.h>
int main(void) {
printf("Hello World!\n");
return 0;
}
The nice thing about using c is that you can choose what compiler you want to use, e.g.
$ export CC=clang
$ export CC=gcc
So you get all of your favorite optimizations too! Beat that tcc -run!
You can also add compiler flags to the shebang, as long as they are terminated with the -- characters:
#!/usr/bin/c -Wall -g -lncurses --
#include <ncurses.h>
int main(void) {
initscr();
/* ... */
return 0;
}
c also uses $CFLAGS and $CPPFLAGS if they are set as well.

#!/usr/bin/env sh
tail -n +$(( $LINENO + 1 )) "$0" | cc -xc - && { ./a.out "$#"; e="$?"; rm ./a.out; exit "$e"; }
#include <stdio.h>
int main(int argc, char const* argv[]) {
printf("Hello world!\n");
return 0;
}
This properly forwards the arguments and the exit code too.

Quite a short proposal would exploit:
The current shell script being the default interpreter for unknown types (without a shebang or a recognizable binary header).
The "#" being a comment in shell and "#if 0" disabling code.
#if 0
F="$(dirname $0)/.$(basename $0).bin"
[ ! -f $F -o $F -ot $0 ] && { c++ "$0" -o "$F" || exit 1 ; }
exec "$F" "$#"
#endif
// Here starts my C++ program :)
#include <iostream>
#include <unistd.h>
using namespace std;
int main(int argc, char **argv) {
if (argv[1])
clog << "Hello " << argv[1] << endl;
else
clog << "hello world" << endl;
}
Then you can chmod +x your .cpp files and then ./run.cpp.
You could easily give flags for the compiler.
The binary is cached in the current directory along with the source, and updated when necessary.
The original arguments are passed to the binary: ./run.cpp Hi
It doesn't reuse the a.out, so that you can have multiple binaries in the same folder.
Uses whatever c++ compiler you have in your system.
The binary starts with "." so that it is hidden from the directory listing.
Problems:
What happens on concurrent executions?

Variatn of John Kugelman can be written in this way:
#!/bin/bash
t=`mktemp`
sed '1,/^\/\/code/d' "$0" | g++ -o "$t" -x c++ - && "$t" "$#"
r=$?
rm -f "$t"
exit $r
//code
#include <stdio.h>
int main() {
printf("Hi\n");
return 0;
}

Here's yet another alternative:
#if 0
TMP=$(mktemp -d)
cc -o ${TMP}/a.out ${0} && ${TMP}/a.out ${#:1} ; RV=${?}
rm -rf ${TMP}
exit ${RV}
#endif
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Hello world\n");
return 0;
}

I know this question is not a recent one, but I decided to throw my answer into the mix anyways.
With Clang and LLVM, there is not any need to write out an intermediate file or call an external helper program/script. (apart from clang/clang++/lli)
You can just pipe the output of clang/clang++ to lli.
#if 0
CXX=clang++
CXXFLAGS="-O2 -Wall -Werror -std=c++17"
CXXARGS="-xc++ -emit-llvm -c -o -"
CXXCMD="$CXX $CXXFLAGS $CXXARGS $0"
LLICMD="lli -force-interpreter -fake-argv0=$0 -"
$CXXCMD | $LLICMD "$#" ; exit $?
#endif
#include <cstdio>
int main (int argc, char **argv) {
printf ("Hello llvm: %d\n", argc);
for (auto i = 0; i < argc; i++) {
printf("%d: %s\n", i, argv[i]);
}
return 3==argc;
}
The above however does not let you use stdin in your c/c++ script.
If bash is your shell, then you can do the following to use stdin:
#if 0
CXX=clang++
CXXFLAGS="-O2 -Wall -Werror -std=c++17"
CXXARGS="-xc++ -emit-llvm -c -o -"
CXXCMD="$CXX $CXXFLAGS $CXXARGS $0"
LLICMD="lli -force-interpreter -fake-argv0=$0"
exec $LLICMD <($CXXCMD) "$#"
#endif
#include <cstdio>
int main (int argc, char **argv) {
printf ("Hello llvm: %d\n", argc);
for (auto i = 0; i < argc; i++) {
printf("%d: %s\n", i, argv[i]);
}
for (int c; EOF != (c=getchar()); putchar(c));
return 3==argc;
}

There are several places that suggest the shebang (#!) should remain but its illegal for the gcc compiler. So several solutions cut it out. In addition it is possible to insert a preprocessor directive that fixes the compiler messages for the case the c code is wrong.
#!/bin/bash
#ifdef 0
xxx=$(mktemp -d)
awk 'BEGIN
{ print "#line 2 \"$0\""; first=1; }
{ if (first) first=0; else print $0 }' $0 |\
g++ -x c++ -o ${xxx} - && ./${xxx} "$#"
rv=$?
\rm ./${xxx}
exit $rv
#endif
#include <iostream>
int main(int argc,char *argv[]) {
std::cout<<"Hello world"<<std::endl;
}

As stated in a previous answer, if you use tcc as your compiler, you can put a shebang #!/usr/bin/tcc -run as the first line of your source file.
However, there is a small problem with that: if you want to compile that same file, gcc will throw an error: invalid preprocessing directive #! (tcc will ignore the shebang and compile just fine).
If you still need to compile with gcc one workaround is to use the tail command to cut off the shebang line from the source file before piping it into gcc:
tail -n+2 helloworld.c | gcc -xc -
Keep in mind that all warnings and/or errors will be off by one line.
You can automate that by creating a bash script that checks whether a file begins with a shebang, something like
if [[ $(head -c2 $1) == '#!' ]]
then
tail -n+2 $1 | gcc -xc -
else
gcc $1
fi
and use that to compile your source instead of directly invoking gcc.

Just wanted to share, thanks to Pedro's explanation on solutions using the #if 0 trick, I have updated my fork on TCC (Sugar C) so that all examples can be called with shebang, finally, with no errors when looking source on the IDE.
Now, code displays beautifully using clangd in VS Code for project sources. Samples first lines look like:
#if 0
/usr/local/bin/sugar `basename $0` $# && exit;
// above is a shebang hack, so you can run: ./args.c <arg 1> <arg 2> <arg N>
#endif
The original intention of this project always has been to use C as if a scripting language using TCC base under the hood, but with a client that prioritizes ram output over file output (without the of -run directive).
You can check out the project at: https://github.com/antonioprates/sugar

I like to use this as the first line at the top of my programs:
For C (technically: gnu C as I've specified it below):
///usr/bin/env ccache gcc -Wall -Wextra -Werror -O3 -std=gnu17 "$0" -o /tmp/a -lm && /tmp/a "$#"; exit
For C++ (technically: gnu++ as I've specified it below):
///usr/bin/env ccache g++ -Wall -Wextra -Werror -O3 -std=gnu++17 "$0" -o /tmp/a -lm && /tmp/a "$#"; exit
ccache helps ensure your compiling is a little more efficient. Install it in Ubuntu with sudo apt update && sudo apt install ccache.
For Go (golang) and some explanations of the lines above, see my other answer here: What's the appropriate Go shebang line?

Related

How can i give command line arguments without using out extension ,not ./a.out 3 4 but like ./a 3 4

int main(int argc, char *argv[])
{
if (argc < 2) {
printf("missing argument\n");
exit(-1);
}
printf("%s %s %s", argv[1], argv[2]);
return 0;
}
Just want to give command line arguments like ./a 3 4 without using .out in linux terminal thanks!!
Assuming your source file was a.c, just use the -o ("output") flag when you compile it, like this:
cc -o a a.c
Or, if you already did
cc a.c
meaning it left it in a.out by default, you can always rename it:
mv a.out a
Of course you can call it anything you want:
cc -o mytestprogram a.c

.gcda files don't merge on multiple runs

I have two main functions that use a common C++ class.
File1: main.cpp
#include <iostream>
#include "HelloAnother.h"
int main() {
HelloAnother::sayHello1();
return 0;
}
File2: main2.cpp
#include <iostream>
#include "HelloAnother.h"
int main() {
HelloAnother::sayHello2();
return 0;
}
File3: HelloAnother.h
#pragma once
class HelloAnother {
public:
static void sayHello1();
static void sayHello2();
};
File4: HelloAnother.cpp
#include <iostream>
#include "HelloAnother.h"
void HelloAnother::sayHello1() {
std::cout << "Hello 1!!!" << std::endl;
}
void HelloAnother::sayHello2() {
std::cout << "Hello 2 !!!" << std::endl;
}
Now I compile two executables:
clang-3.8 -o main -fprofile-arcs -ftest-coverage --coverage -g -fPIC -lstdc++ main.cpp HelloAnother.cpp
clang-3.8 -o main2 -fprofile-arcs -ftest-coverage --coverage -g -fPIC -lstdc++ main2.cpp HelloAnother.cpp
Now, I run ./main
Hello 1!!!
When I rerun ./main
Hello 1!!!
profiling: /media/sf_ubuntu-shared/test-profiling/main.gcda: cannot map: Invalid argument
profiling: /media/sf_ubuntu-shared/test-profiling/HelloAnother.gcda: cannot map: Invalid argument
One second run, I get this error (above) in trying to create/merge .gcda files.
Now, If I try to run ./main2
Hello 2 !!!
profiling: /media/sf_ubuntu-shared/test-profiling/HelloAnother.gcda: cannot map: Invalid argument
When I generate the code coverage report, the call to second function doesn't show up as if the call wasn't made.
Can anyone help me debug this issue pls? The issue seems to be related to merging of .gcda files on multiple runs, but not sure how to solve it.
I also tried clang-3.5 but with same results.
After a lot of searching and trial/error this is what works for me:
Compile first executable, run it. This generates HelloAnother.gcda and main.gcda files.
Execute lcov --gcov-tool=gcov-4.4 --directory . --capture --output-file coverage.main.info
rm -rf *.gcda; rm -rf *.gcno
Compile second executable (main2.cpp), run it. This generates another HelloAnother.gcda and a main2.gcda file.
Execute lcov --gcov-tool=gcov-4.4 --directory . --capture --output-file coverage.main2.info
Now to generate nice looking html report do: genhtml -o coverage coverage.main.info coverage.main2.info
Your problem is that you compile the shared file (HelloAnother.cc) twice and gcov fails to understand that two copies of HelloAnother.o inside main1 and main2 need to be shared.
Instead, compile the shared code once and link it into each executable:
$ g++ --coverage -c HelloAnother.cc
$ g++ --coverage main1.cc HelloAnother.o -o main1
$ g++ --coverage main2.cc HelloAnother.o -o main2
$ ./main1
Hello 1!!!
$ ./main2
Hello 2 !!!
$ gcov --stdout HelloAnother.gcno
...
1: 4:void HelloAnother::sayHello1() {
1: 5: std::cout << "Hello 1!!!" << std::endl;
1: 6:}
-: 7:
1: 8:void HelloAnother::sayHello2() {
1: 9: std::cout << "Hello 2 !!!" << std::endl;
1: 10:}
-: 11:

run rsync through execvp: StrictHostKeyChecking=no: unknown option

I am trying to run rsync through execvp with StrictHostKeyChecking option.
This is my code:
#include <unistd.h>
int main() {
char *argv[] = {"rsync",
"remote_user#1.2.4.5:/tmp",
"/home/tmp/",
"-e 'ssh -o StrictHostKeyChecking=no'",
0};
execvp("rsync", argv);
}
I am getting this error:
rsync: -e '-o StrictHostKeyChecking=no': unknown option
rsync error: syntax or usage error (code 1) at main.c(1422) [client=3.0.6]
I have tried another way:
#include <unistd.h>
int main() {
char *argv[] = {"rsync",
"remote_user#1.2.4.5:/tmp",
"/home/tmp/",
"-e",
"'ssh -o StrictHostKeyChecking=no'",
0};
execvp("rsync", argv);
}
But now it is failing with error:
rsync: Failed to exec ssh -o StrictHostKeyChecking=no: No such file or directory (2) rsync error: error in IPC code (code 14) at pipe.c(84) [sender=3.0.6]
Why it don't understand StrictHostKeyChecking option?
rsync expects to receive the options first, followed by the hosts. You're doing it backwards: first you need to specify -e and -o.
You also shouldn't be single-quoting the -o option: that is needed when invoking it from bash, to prevent bash from interpreting the arguments and splitting them into separate argv[] entries. Think about it: when bash sees '-o StrictHostKeyChecking=no', it passes -o StrictHostKeyChecking=no as a single argv[] entry, without the single quotes (because the single quotes is your way to tell the shell that you don't want argument splitting).
Last, but not least, you should check that execvp(3) didn't fail.
So, this is what you need:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char *argv[] = {
"rsync",
"-e",
"ssh -o StrictHostKeyChecking=no",
"remote_user#1.2.4.5:/tmp",
"/home/tmp/",
NULL
};
if (execvp("rsync", argv) < 0) {
perror("rsync(1) error");
exit(EXIT_FAILURE);
}
return 0;
}

swig c++ to perl : how to use c++11 string STL functions

I would like to call c++ functions from a website that uses Perl.
The c++ code works fine, I am getting troubles from SWIG wrapper regarding some new function from c++11 in < string> STL. in this case stoi(string), while the problem is the same with other functions like string.pop_back(), stol... all functions brought to < string> with c++11 vesrsion.
how to make SWIG take into account those new functions so that it can compile ?
Here is the error message I got
error: ‘stoi’ is not a member of ‘std’
/* --- source fonctions.cpp --- */
bool checkRIB(std::string word){
cout << "verification du rib : "<< word<<endl;
if (word.size()!=23) return false;
for (size_t i=0; i!=word.size(); i++) {
if (!isdigit(word[i])){
if ((word[i]>='A'&&word[i]<='I')){
word[i]= (int)(word[i]-'A')%10+'1';
}else if ((word[i]>='J'&&word[i]<='R')){
word[i]= (int)(word[i]-'J')%10+'1';
} else if ((word[i]>='S'&&word[i]<='Z')){
word[i]= (int)(word[i]-'S')%10+'2';
} else cout << "mauvais code"<<endl;
}
}
return ( (97-((89*std::stoi(word.substr(0,5)) + 15*std::stoi(word.substr(5,5))+3*std::stol(word.substr(10,11))) % 97)) == std::stoi(word.substr(21,2)) );
}
/* --- header fonctions.h--- */
#ifndef DEF_FONCTIONS
#define DEF_FONCTIONS
#include <fstream> // pour lecture / ecriture de fichiers
#include <iostream>
#include <math.h>
bool checkRIB(std::string word);
#endif
/* --- interface code interface.i --- */
%module interface
%include"std_string.i"
%include "std_map.i"
%include "std_vector.i"
%{
/* Put header files here or function declarations like below */
bool checkRIB(std::string word);
}
bool seRessemblent(const std::string &s1, const std::string & s2, float seuil=0.65);
%}
bool checkRIB(std::string word);
and the foolowing steps for the compilation (on Ubuntu) :
1% swig -c++ -perl5 interface.i
2% g++ -c `perl -MConfig -e 'print join(" ", #Config{qw(ccflags optimize cccdlflags)}, "-I$Config{archlib}/CORE")'` fonctions.cpp interface_wrap.cxx
(here error : *error: ‘stoi’ is not a member of ‘std’*)
3% g++ `perl -MConfig -e 'print $Config{lddlflags}'` fonctions.o interface_wrap.o -o interface.so
The interface is working fine on other functions (Not displayed for space reason)
Thank you for helping
Alexis
I found a way to work around the problem:
I split the compilation procedure from
1% swig -c++ -perl5 interface.i
2% g++ -c `perl -MConfig -e 'print join(" ", #Config{qw(ccflags optimize cccdlflags)}, "-I$Config{archlib}/CORE")'` fonctions.cpp interface_wrap.cxx
(here error : *error: ‘stoi’ is not a member of ‘std’*)
3% g++ `perl -MConfig -e 'print $Config{lddlflags}'` fonctions.o interface_wrap.o -o interface.so
to
1% swig -c++ -perl5 interface.i
2% g++ -c -fPIC fonctions.cpp -std=c++11
3% g++ -c `perl -MConfig -e 'print join(" ", #Config{qw(ccflags optimize cccdlflags)}, "-I$Config{archlib}/CORE")'` interface_wrap.cxx
4% g++ `perl -MConfig -e 'print $Config{lddlflags}'` fonctions.o interface_wrap.o -o interface.so
This way the ordinary c++ code is compiled in c++11 as needed.
the -fPIC option is to be used so that the libraries can be joined.
I could not find a way to use c++11with the interface wrapper though.

Include cuda kernel in my project

I have this c++ project in which I call a cuda kernel by means of a wrapper function.
My c++ file looks like this (this is extern.cc):
#include "extern.h"
#include "qc/operator.h"
#include "qc/quStates.h"
#include "gpu.h"
...
ROUTINE(ext_bit) {
int i;
quState *qbit;
PAR_QUSTATE(q,"q");
opBit *op;
tComplex I(0,1);
tComplex sg= inv ? -1 : 1;
char c=(def->id())[0];
if(def->id().length()!=1) c='?';
switch(c) {
case 'H': op=new opBit(1,1,1,-1,sqrt(0.5)); break;
case 'X': op=new opBit(0,1,1,0); break;
case 'Y': op=new opBit(0,-I,I,0); break;
case 'Z': op=new opBit(1,0,0,-1); break;
case 'S': op=new opBit(1,0,0,sg*I); break;
case 'T': op=new opBit(1,0,0,sqrt(0.5)+sg*sqrt(0.5)*I); break;
case '?':
default: EXTERR("unknown single qubit operator "+def->id());
}
// This is where I call my wrapper function
// the error that I get is: expected primary-expression before ',' token
gpucaller(opBit, q);
qcl_delete(op);
return 0;
}
where "gpucaller" is my wrapper function that calls the kernel, both defined in cuda_kernel.cu:
/* compiling with:
nvcc -arch sm_11 -c -I"/home/glu/NVIDIA_GPU_Computing_SDK/C/common/inc" -I"." -I"./qc" -I"/usr/local/cuda/include" -o cuda_kernel.o cuda_kernel.cu
*/
#ifndef _CUDA_KERNEL_H_
#define _CUDA_KERNEL_H_
#define MAX_QUBITS 25
#define BLOCKDIM 512
#define MAX_TERMS_PER_BLOCK (2*BLOCKDIM)
#define THREAD_MASK (~0ul << 1)
// includes
#include <cutil_inline.h>
#include "gpu.h"
__constant__ float devOpBit[2][2];
__global__ void qcl1(cuFloatComplex *a, int N, int qbCount, int blockGrpSize, int k)
{
//int idx = blockIdx.x * BLOCKDIM + threadIdx.x;
//int tx = threadIdx.x;
cuFloatComplex t0_0, t0_1, t1_0, t1_1;
int x0_idx, x1_idx;
int i, grpSize, b0_idx, b1_idx;
__shared__ cuFloatComplex aS[MAX_TERMS_PER_BLOCK];
...
}
void gpucaller(opBit* op, quBaseState* q) {
// make an operator copy
float** myOpBit = (float**)op->getDeviceReadyOpBit();
unsigned int timer = 0;
cuFloatComplex *a_d;
long int N = 1 << q->mapbits();
int size = sizeof(cuFloatComplex) * N;
// start timer
cutilCheckError( cutCreateTimer( &timer));
cutilCheckError( cutStartTimer( timer));
// allocate device memory
cudaMalloc((void**)&a_d,size);
// copy host memory to device
cudaMemcpy(a_d, q->termsarray, size, cudaMemcpyHostToDevice);
// copy quantic operator to constant memory
cutilSafeCall( cudaMemcpyToSymbol(devOpBit, myOpBit, 2*sizeof(float[2]), 0) );
printf("Cuda errors: %s\n", cudaGetErrorString( cudaGetLastError() ) );
// setup execution parameters
dim3 dimBlock(BLOCKDIM, 1, 1);
int n_blocks = N/MAX_TERMS_PER_BLOCK + (N%MAX_TERMS_PER_BLOCK == 0 ? 0:1);
dim3 dimGrid(n_blocks, 1, 1);
...
// execute the kernel
qcl1<<< dimGrid, dimBlock >>>(a_d, N, gates, blockGrpSize, k);
// check if kernel execution generated and error
cutilCheckMsg("Kernel execution failed");
...
// copy result from device to host
cudaMemcpy(q->termsarray, a_d, size, cudaMemcpyDeviceToHost);
// stop timer
cutilCheckError( cutStopTimer( timer));
//printf( "GPU Processing time: %f (ms)\n", cutGetTimerValue( timer));
cutilCheckError( cutDeleteTimer( timer));
// cleanup memory on device
cudaFree(a_d);
cudaThreadExit();
}
#endif // #ifndef _CUDA_KERNEL_H_
and "gpu.h" has the following content:
#ifndef _GPU_H_
#define _GPU_H_
#include "qc/operator.h"
#include "qc/qustates.h"
void gpucaller(opBit* op, quBaseState* q);
#endif // #ifndef _GPU_H_
I don't include the .cu file in my c++ file, I only include the .h file (gpu.h - contains the prototype of my kernel caller function) in both the c++ and the .cu files.
I compile the .cu file with nvcc, and link the resulting .o file in my project's Makefile.
Also, I didn't forget to add the "-lcudart" flag to the Makefile.
The problem is that when I compile my main project, I get this error:
expected primary-expression before ',' token
and is referring to the line in extern.cc where I call the "gpucaller" function.
Does anyone know how to get this right?
EDIT: I've tried compiling again, this time removing the arguments from the gpucaller's function definition (and obviously not passing any arguments to the function, which is wrong because I need to pass arguments). It compiled just fine.
So the problem is that gpucaller's argument types aren't recognized, I have no idea why (I've included the headers where the arguments' types are declared, ie "qc/operator.h" and "qc/quStates.h"). Does anyone have a solution to this?
My project's Makefile is this:
VERSION=0.6.3
# Directory for Standard .qcl files
QCLDIR = /usr/local/lib/qcl
# Path for qcl binaries
QCLBIN = /usr/local/bin
ARCH = `g++ -dumpmachine || echo bin`
# Comment out if you want to compile for a different target architecture
# To build libqc.a, you will also have to edit qc/Makefile!
#ARCH = i686-linux
#ARCHOPT = -m32 -march=i686
# Debugging and optimization options
#DEBUG = -g -pg -DQCL_DEBUG -DQC_DEBUG
#DEBUG = -g -DQCL_DEBUG -DQC_DEBUG
DEBUG = -O2 -g -DQCL_DEBUG -DQC_DEBUG
#DEBUG = -O2
# Plotting support
#
# Comment out if you don't have GNU libplotter and X
PLOPT = -DQCL_PLOT
PLLIB = -L/usr/X11/lib -lplotter
# Readline support
#
# Comment out if you don't have GNU readline on your system
# explicit linking against libtermcap or libncurses may be required
RLOPT = -DQCL_USE_READLINE
#RLLIB = -lreadline
RLLIB = -lreadline -lncurses
# Interrupt support
#
# Comment out if your system doesn't support ANSI C signal handling
IRQOPT = -DQCL_IRQ
# Replace with lex and yacc on non-GNU systems (untested)
LEX = flex
YACC = bison
INSTALL = install
##### You shouldn't have to edit the stuff below #####
DATE = `date +"%y.%m.%d-%H%M"`
QCDIR = qc
QCLIB = $(QCDIR)/libqc.a
QCLINC = lib
#CXX = g++
#CPP = $(CC) -E
CXXFLAGS = -c $(ARCHOPT) -Wall $(DEBUG) $(PLOPT) $(RLOPT) $(IRQOPT) -I$(QCDIR) -DDEF_INCLUDE_PATH="\"$(QCLDIR)\""
LDFLAGS = $(ARCHOPT) -L$(QCDIR) $(DEBUG) $(PLLIB) -lm -lfl -lqc $(RLLIB) -L"/usr/local/cuda/lib" -lcudart
FILESCC = $(wildcard *.cc)
FILESH = $(wildcard *.h)
SOURCE = $(FILESCC) $(FILESH) qcl.lex qcl.y Makefile
OBJECTS = types.o syntax.o typcheck.o symbols.o error.o \
lex.o yacc.o print.o quheap.o extern.o eval.o exec.o \
parse.o options.o debug.o cond.o dump.o plot.o format.o cuda_kernel.o
all: do-it-all
ifeq (.depend,$(wildcard .depend))
include .depend
do-it-all: build
else
do-it-all: dep
$(MAKE)
endif
#### Rules for depend
dep: lex.cc yacc.cc yacc.h $(QCLIB)
for i in *.cc; do \
$(CPP) -I$(QCDIR) -MM $$i; \
done > .depend
lex.cc: qcl.lex yacc.h
$(LEX) -olex.cc qcl.lex
yacc.cc: qcl.y
$(YACC) -t -d -o yacc.cc qcl.y
yacc.h: yacc.cc
mv yacc.*?h yacc.h
$(QCLIB):
cd $(QCDIR) && $(MAKE) libqc.a
#### Rules for build
build: qcl $(QCLINC)/default.qcl
qcl: $(OBJECTS) qcl.o $(QCLIB)
$(CXX) $(OBJECTS) qcl.o $(LDFLAGS) -o qcl
$(QCLINC)/default.qcl: extern.cc
grep "^//!" extern.cc | cut -c5- > $(QCLINC)/default.qcl
checkinst:
[ -f ./qcl -a -f $(QCLINC)/default.qcl ] || $(MAKE) build
install: checkinst
$(INSTALL) -m 0755 -d $(QCLBIN) $(QCLDIR)
$(INSTALL) -m 0755 ./qcl $(QCLBIN)
$(INSTALL) -m 0644 ./$(QCLINC)/*.qcl $(QCLDIR)
uninstall:
-rm -f $(QCLBIN)/qcl
-rm -f $(QCLDIR)/*.qcl
-rmdir $(QCLDIR)
#### Other Functions
edit:
nedit $(SOURCE) &
clean:
rm -f *.o lex.* yacc.*
cd $(QCDIR) && $(MAKE) clean
clear: clean
rm -f qcl $(QCLINC)/default.qcl .depend
cd $(QCDIR) && $(MAKE) clear
dist-src: dep
mkdir qcl-$(VERSION)
cp README CHANGES COPYING .depend $(SOURCE) qcl-$(VERSION)
mkdir qcl-$(VERSION)/qc
cp qc/Makefile qc/*.h qc/*.cc qcl-$(VERSION)/qc
cp -r lib qcl-$(VERSION)
tar czf qcl-$(VERSION).tgz --owner=0 --group=0 qcl-$(VERSION)
rm -r qcl-$(VERSION)
dist-bin: build
mkdir qcl-$(VERSION)-$(ARCH)
cp Makefile README CHANGES COPYING qcl qcl-$(VERSION)-$(ARCH)
cp -r lib qcl-$(VERSION)-$(ARCH)
tar czf qcl-$(VERSION)-$(ARCH).tgz --owner=0 --group=0 qcl-$(VERSION)-$(ARCH)
rm -r qcl-$(VERSION)-$(ARCH)
upload: dist-src
scp qcl-$(VERSION)*.tgz oemer#tph.tuwien.ac.at:html/tgz
scp: dist-src
scp qcl-$(VERSION).tgz oemer#tph.tuwien.ac.at:bak/qcl-$(DATE).tgz
The only changes that I've added to the original Makefile is adding "cuda_kernel.o" to the OBJECTS' line, and adding the "-lcudart" flag to LDFLAGS.
UPDATE: Thanks harrism for helping me out. I was passing a type as a parameter.
gpucaller(opBit, q);
You are passing a type name (opBit) as a function parameter, which is not valid C or C++. It looks like you need to do this instead:
gpucaller(op, q);
Does it literally look like this in cuda.h?
void gpucaller(type1 param1, type2 param2);
Are type1 and type2 declared anywhere so that your regular C++ compiler know what these types are? If not, then you'd get an error like you're saying you're getting.
Your problem code is pretty big and complex at the moment. Try to strip it down to a more simple failure case and update your question once you have that. It'll make it easier to attempt reproduction. Strip out the cuda timer code, the switch case, replace implementation details with ... where it doesn't matter, etc.
I compile with msvc and nvcc then link with icl; so if you can make a simple example I can see if it compiles with a totally different compiler setup. That should narrow down the problem.
Even though renaming your own header cuda.h to somethingspecific.h didn't help, I don't think it's a good idea to leave it as cuda.h. It's confusing and a potential source of problems.