I have a visual studio c++ project (with VS 2010 and insight 2) which contains a cuda file. Here's the code
Hello.h :
#pragma once
#pragma warning(push)
#pragma warning(disable:4996)
#include "thrust\device_vector.h"
#pragma warning(pop)
class Hello
{
public:
Hello( const thrust::host_vector<unsigned long>& data );
unsigned long Sum();
unsigned long Max();
private:
thrust::device_vector<unsigned long> m_data;
}
Hello.cu :
#include "thrust\host_vector.h"
#include "thrust\device_vector.h"
#include "thrust\extrema.h"
#include "Hello.h"
using namespace ::thrust;
Hello::Hello( const thrust::host_vector<unsigned long>& data )
: m_data( data.cbegin(), data.cend() )
{
}
unsigned long
Hello::Sum()
{
return( reduce( m_data.cbegin(), m_data.cend(),
( unsigned long )0,
plus<unsigned long>() ) );
}
unsigned long
Hello::Max()
{
return( *max_element( m_data.cbegin(), m_data.cend() ) );
}
and finally main.cpp :
#ifdef _WIN32
#define WINDOWS _LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ppl.h> //parallel patterns library
#include "Hello.h"
using namespace ::Concurrency;
int
main( int argc, char** argv )
{
printf( "Generating data...\n" );
thrust::host_vector<unsigned long> host_data( 100000 );
thrust::generate( host_data.begin(), host_data.end(), rand );
printf( "generated %d numbers\n", host_data.size() );
parallel_invoke(
[host_data]()
{
printf( "\nRunning host code...\n" );
unsigned long host_result = thrust::reduce( host_data.cbegin(),
host_data.cend(), 0, thrust::plus<unsigned long>() );
printf( "The sum is %d\n", host_result );
host_result = *thrust::max_element( host_data.cbegin(),
host_data.cend(), thrust::less<unsigned long>() );
printf( "The max is %d\n", host_result );
},
[host_data]()
{
printf( "\nCopying data to device...\n" );
Hello hello( host_data );
printf( "\nRunning CUDA device code...\n" );
unsigned long device_result = hello.Sum();
printf( "The sum is %d\n", device_result );
printf( "\nRunning CUDA device code...\n" );
device_result = hello.Max();
printf( "The max is %d\n", device_result );
}
);
return( 0 );
}
This code comes from : here
My problem is that when I build the project, it gives me this error:
Hello.cu(5): fatal error C1083: Cannot open include file: 'Hello.h': No such file or directory
However, when I right click on the "include "Hello.h"" it finds the file just fine.
I've added the folder where my .h are in the additionnal include directories of the project. So I really don't know why it couldn't open the file.
I don't know if it's more of a configuration problem of just maybe a c++ thing I forgot...
Your .cu file will have most likely have a custom build rule to make use of NVCC. Right-click the .cu file and look at its properties. The build rule will again contain a section for additional include directories. Make sure the directory containing your header is present there as well.
Related
I have a small piece of code, which gives this error when trying to make, here is the CMakelists.txt being used:
cmake_minimum_required(VERSION 2.8) #Specify the minimum CM$
project(gaussian) $
find_package(CUDA REQUIRED) #find the CUDA $
find_package(ITK REQUIRED)
include( ${ITK_USE_FILE} )
#message("Debug: ITK ${ITK_DIR}")
include_directories(${CUDA_INCLUDE_DIRS}) #Specify the CUDA include direc$
add_executable(gaussian source/main.cu) #create an executabl$
#specify any additional libraries here (CUFFT and CUBLAS can be useful)
target_link_libraries(gaussian ${CUDA_cufft_LIBRARY} ${CUDA_cublas_LIBRARY} ${I$
The main.cu file is below:
#include <fstream>
#include <cuda.h>
#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <ctime>
#include <cuda_runtime_api.h>
#include <cufft.h>
#include "itkImage.h"
using namespace std;
static void HandleError( cudaError_t err, const char *file, int line )
{
if (err != cudaSuccess)
cout<<cudaGetErrorString(err)<<" in "<< file <<" at line "<< line<<endl;
}
#define HANDLE_ERROR( err ) (HandleError( err, __FILE__, __LINE__ ))
int main(int argc, char* argv[])
{
typedef itk::Image< unsigned short, 3 > ImageType;
ImageType::Pointer image = ImageType::New();
cout << "ITK Hello World !" << endl;
int nDevices;
cout<<"DEVICE SPECIFICATIONS: "<<endl<<endl;
HANDLE_ERROR(cudaGetDeviceCount(&nDevices));
return 0;
}
While building, the linkers are set. I am unable to figure out what is wrong here.
I found the issue here, firstly as pointed I needed to use cuda_add_executable, instead of add_executable. Doing that and building, I get errors like:
overriding itk::ImageBase<VImageDimension>::Pointer
itk::ImageBase<VImageDimension>::CreateAnother() const [with unsigned int VImageDimension = 3u, itk::ImageBase<VImageDimension>::Pointer = itk::SmartPointer<itk::ImageBase<3u> >]
These are because the CUDA compiler has trouble with the C++ features used b y ITK. Using the ITK features in a .cxx file and calling CUDA functions in .cu file helped.
Credits: http://public.kitware.com/pipermail/insight-developers/2012-October/022116.html
I have 2 files and i want each core read its own file ( each file has 5 lines ) and display its content
in this code I have 2 cores ( core0 , core1) the output core 0 read the content of core1 ( 5 lines ). and core1 read 4 lines from his content.
I tried to make it as if else conditions and each file has its own reader but the same problem still exist.what should i do ?
#include <vector>
#include <stdio.h>
#include <time.h>
#include <mpi.h>
#include <omp.h>
#include <fstream>
#include <iostream>
using namespace std;
void func2(int CoreID )
{
int iFace;
int iFaces=0;
if (CoreID==0)
{
FILE* imgListFile = 0;
char imgFilename[5012];
char actualPath[90]="C:\\DaliaDaliaSh\\TrainingFiles\\File10img_0_C";
strcat(actualPath , "0.txt");
imgListFile= freopen(actualPath , "r",stdin);
while (fgets(imgFilename, 5012, imgListFile))
{
++iFaces;
printf( "** Core = %d , Path = %s\n" , CoreID , imgFilename );
}
rewind(imgListFile);
}
else if (CoreID==1)
{
FILE* imgListFile2 = 0;
char imgFilename2[5012];
char actualPath2[90]="C:\\DaliaDaliaSh\\TrainingFiles\\File10img_0_C";
strcat(actualPath2 , "1.txt");
imgListFile2= freopen(actualPath2 , "r",stdin);
while (fgets(imgFilename2, 5012, imgListFile2))
{
++iFaces;
printf( "** Core = %d , Path = %s\n" , CoreID , imgFilename2 );
}
rewind(imgListFile2);
}
//printf ("*ID = %d open actualPath= %s\n" , myId , actualPath);
printf("core %d , iFaces= %d \n", CoreID , iFaces);
}
void main(int argc,char **argv)
{
MPI::Init(argc,argv);
int threadnum=2;
omp_set_num_threads(threadnum);
#pragma omp parallel
{
int CoreID = omp_get_thread_num();
int x ;
func2(CoreID);
cout <<"####after call func inside pragma \n" ;
}
MPI ::Finalize();
}
You are doing freopen on stdin. Thus, both cores will use the same stream and the file read will depend upon which core opened the stream first/last [which is a race condition].
Do a regular fopen instead and they won't conflict [as they're doing now]
This question already has answers here:
Why does global variables in a header file cause link error?
(5 answers)
Closed 7 years ago.
I know, there are a lot of similar problems and solutions already on SO, and I read them, but none of them helped me solve my problem.
I created a class for logging.
Here is Logger.h
#ifndef LOGGER_H
#define LOGGER_H
namespace Logger
{
namespace debug
{
int Error = 0, OtherNumber;
class log
{
public: // Methods
void Save();
private: // Members
static int indentation;
const std::wstring context;
int Type, LineNumber;
public: // Constructor, Destructor
log( const std::wstring& context, int LineNumber, int Type );
~log();
};//class log
}//namespace debug
}//namespace Logger
#endif //LOGGER_H
Logger.cpp
#include "stdafx.h"
#include "Logger.h"
namespace Logger
{
namespace debug
{
log::log( const std::wstring& ctx, int linenr, int type ): context( ctx ), LineNumber( linenr ), Type( type )
{
printf("\nLogging start! Context = %ls - Line = %d - Type = %d", context.c_str(), LineNumber, Type );
}
log::~log()
{
printf( "\nLogging end! Context = %ls - Line = %d - Type = %d", context.c_str(), LineNumber, Type );
printf( "\nUsing Error here =%d", Error );
}
void log::Save()
{
FILE *fp = NULL;
fclose( fp );
fp = fopen( "mylogfile.log", "a" );
}
}//namespace debug
}//namespace Logger
Then in main.h I have:
#ifndef MYAPP_H
#define MYAPP_H
#include "Logger.h"
#define WIDEN2( x ) L ## x
#define WIDEN( x ) WIDEN2( x )
#define WFILE WIDEN( __FILE__ )
#define __STR2WSTR( str ) L##str
#define _STR2WSTR(str) __STR2WSTR(str)
#define WFUNCTION _STR2WSTR( __FUNCTION__ )
#define DEBUGLOG_START( Type ) Logger::debug::log _debugLog( WFUNCTION, __LINE__, Type );
#define DEBUGLOG_SAVE { _debugLog.Save(); }
#endif //MYAPP_H
And finally in main.cpp I have:
#include "Test_UserPart.h"
int _tmain(int argc, _TCHAR* argv[])
{
DEBUGLOG_START( 1 )
Logger::debug::OtherNumber = 10;
_getch();
return 0;
}
When I want to compile it I get the error error LNK2005: "int Logger::debug::Error" (?Error#debug#Logger##3HA) already defined in Logger.obj ...MyApp.obj
So as far as I see, I didn't make any circular includes. But why do I get this error?
Thanks!
You're defining variables in the header, leading to multiple definitions when that header is included from more than one source file. Instead, declare them in the header:
extern int Error = 0, OtherNumber;
^^^^^^
and define them in just one source file. Or stop using global variables.
i need to print events on a folder with multiple subfolders. how to do it recursivly? Please print a c++ code. I am stucked!! Every time the evet is poped i need to open the subfolder, take the file and copy it into another directory. I don't want to list all the subfolders in every 2 seconds and find the files if there are any. Is not efficient. I need to use a monitor folder. Please help
The director that i want to monitor has multiple subfolders. Each subfolder has another subfolder that could contain in a moment of time a file. MainFolder->Subfolders->each subfolder-> subfolder -> file.
Here is the code I have for he moment:
/*
*/
#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <sys/inotify.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
using namespace std;
vector<string> SS;
void *print_message_function( void *ptr );
int main(int argc, char **argv ){
pthread_t t1;
int fd,fd1,wd,wd1,i=0,i1=0,len=0,len1=0;
int length;
char pathname[100],buf[1024],buf1[1024];
int data;
struct inotify_event *event;
char *message1 = "Thread 1";
FILE *fr;
// fd=inotify_init1(IN_NONBLOCK);//--rewrite
fd = inotify_init();
/* watch /test directory for any activity and report it back to me */
wd=inotify_add_watch(fd,"/home/MainFoder/",IN_ALL_EVENTS);
// int flag=0;
// char*ev="";
//wd=inotifytools_watch_recursively_with_exclude("/home/MainFolder/",IN_ALL_EVENTS);
while(1)
{
//sleep(30);
//read 1024 bytes of events from fd into buf
i=0;
len=read(fd,buf,1024);
while(i<len){
event=(struct inotify_event *) &buf[i];
/* watch /test directory for any activity and report it back to me */
/* check for changes */
{
if((event->mask & IN_OPEN) ||(event->mask & IN_CREATE))
{
printf("\n %s :was opened\n",event->name);
SS.push_back(event->name);
}
}
/* update index to start of next event */
i+=sizeof(struct inotify_event)+event->len;
}
vector<string>::const_iterator cii;
for(cii=SS.begin(); cii!=SS.end(); cii++)
{
wd1 = watch_from_filename(*ci);
}
/*
vector<string>::const_iterator cii;
for(cii=SS.begin(); cii!=SS.end(); cii++)
{
cout <<"HERE:"<< *cii << endl;
}
*/
int iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &t1, NULL, print_message_function, (void*) message1);
}
}
void *print_message_function( void *ptr )
{
vector<string>::const_iterator cii;
for(cii=SS.begin(); cii!=SS.end(); cii++)
{
cout <<"HERE:"<< *cii << endl;
std::string path=exec
}
}
This working sample on Github does what you're looking for: inotify-example.cpp
On CREATE events, the current wd (watch descriptor), plus the inotify_event wd and name components, are added to a Watch object (see sample).
The class includes methods to lookup wd and names in several ways.
This snippet shows how CREATE/DELETE events are handled:
if ( event->mask & IN_CREATE ) {
current_dir = watch.get(event->wd);
if ( event->mask & IN_ISDIR ) {
new_dir = current_dir + "/" + event->name;
wd = inotify_add_watch( fd, new_dir.c_str(), WATCH_FLAGS );
watch.insert( event->wd, event->name, wd );
total_dir_events++;
printf( "New directory %s created.\n", new_dir.c_str() );
} else {
total_file_events++;
printf( "New file %s/%s created.\n", current_dir.c_str(), event->name );
}
} else if ( event->mask & IN_DELETE ) {
if ( event->mask & IN_ISDIR ) {
new_dir = watch.erase( event->wd, event->name, &wd );
inotify_rm_watch( fd, wd );
total_dir_events--;
printf( "Directory %s deleted.\n", new_dir.c_str() );
} else {
current_dir = watch.get(event->wd);
total_file_events--;
printf( "File %s/%s deleted.\n", current_dir.c_str(), event->name );
}
}
You can do it in two steps:
Detect all the changes you're interested in on the root directory, plus (if not already included) creations (IN_CREATE).
If the creation is a directory, do the whole algorithm on it.
I have written the code for you. Now, you have to do only one change in this code. Just give path of your directory in main function.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#include <limits.h>
#include<sys/stat.h>
#include<dirent.h>
#include<time.h>
#include<string.h>
#include<unistd.h>
#define MAX_EVENTS 1024 /*Max. number of events to process at one go*/
#define LEN_NAME 16 /*Assuming that the length of the filename won't exceed 16 bytes*/
#define EVENT_SIZE ( sizeof (struct inotify_event) ) /*size of one event*/
#define BUF_LEN ( MAX_EVENTS * ( EVENT_SIZE + LEN_NAME )) /*buffer to store the data of events*/
void monitor(char *);
int evnt_mon(char *);
void main()
{
if(fork()==0)
evnt_mon("./usssb");// give path of your directory which you want to monitor
monitor("./usssb");// give path of your directory which you want to monitor
while(1);
}
void monitor(char * rt_dir)
{
struct stat st;
DIR *dirp;
struct dirent *dp;
char str[100][100]={ };
char temp[100];
char str1[500]=" ";
int i=0,j=0,src_ret=9,src_ret1=9;
strcpy(str1,rt_dir);
dirp=opendir(str1);
if(dirp==NULL)
{
perror("opendir");
return;
}
while(1)
{
dp=readdir(dirp);
if(dp==NULL)
break;
if((strcmp(dp->d_name,".\0")==0) || (strcmp(dp->d_name,"..")==0))
continue;
if((dp->d_type==DT_DIR)&&((strcmp(dp->d_name,".")!=0)&&(strcmp(dp->d_name,"..")!=0)))
{
strcat(str[i],str1);
strcat(str[i],"/");
strcat(str[i],dp->d_name);
if(fork()==0)
{
evnt_mon(str[i]);
}
i++;
}
}
closedir(dirp);
if(i>0)
{
for(j=0;j<i;j++)
{
monitor(str[j]);
}
}
}
int evnt_mon(char *argv)
{
int length, i = 0, wd;
int fd;
char buffer[BUF_LEN];
/* Initialize Inotify*/
fd = inotify_init();
if ( fd < 0 )
{
perror( "Couldn't initialize inotify");
}
/* add watch to starting directory */
wd = inotify_add_watch(fd, argv, IN_CREATE | IN_MODIFY | IN_DELETE);
if (wd == -1)
{
printf("Couldn't add watch to %s\n",argv);
}
else
{
printf("Watching:: %s\n",argv);
}
/* do it forever*/
while(1)
{
i = 0;
length = read( fd, buffer, BUF_LEN );
if ( length < 0 )
{
perror( "read" );
}
while ( i < length )
{
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
if ( event->len )
{
if ( event->mask & IN_CREATE)
{
if (event->mask & IN_ISDIR)
{
printf( "The directory %s was Created in %s.\n", event->name,argv );
if(fork()==0)
{
char p[100]=" ";
strcpy(p,argv);
strcat(p,"/");
strcat(p,event->name);
evnt_mon(p);
}
}
else
printf( "The file %s was Created with WD %d\n", event->name, event->wd );
}
if ( event->mask & IN_MODIFY)
{
if (event->mask & IN_ISDIR)
printf( "The directory %s was modified.\n", event->name );
else
printf( "The file %s was modified with WD %d\n", event->name, event->wd );
}
if ( event->mask & IN_DELETE)
{
if (event->mask & IN_ISDIR)
printf( "The directory %s was deleted from %s.\n", event->name,argv );
else
printf( "The file %s was deleted with WD %d\n", event->name, event->wd );
}
i += EVENT_SIZE + event->len;
}
}
}
/* Clean up*/
inotify_rm_watch( fd, wd );
close( fd );
return 0;
}
You might use the fanotify API. It allows you to monitor a complete mount. The only drawback is that you need to be root.
To address the problem stated by ribram (the 'hole':)). one possible solution i can think of is that we can do a combination of 'polling the directory' and 'using inotify'... i.e. Each time a directory is detected (directory only, don't do it for files):
add a watchpoint for the newly detected directory to inotify
'poll' (or 'scan') the newly detected directory (man readdir()) to see if there're already items (files, directories) created. Those are possibly the ones that are missing.
Note that to build an 'air-tight' case, the above steps' order is important. you need to add the watchpoint first than scan ... This will guarantee that an item is picked up by either 'scan' or inotify or both. In that case you may also need to aware of the dups. i.e. the same item can be both yielded by the scan and the inotify
OKay, so I'm trying to set some global variables that can be accessed by the rest of my program by including a header file. However, XCode is telling me that I have duplicate symbols. Can anyone help?
Error: Duplicate symbol _ArrowKey in /Path/to/MKDBControlInterface.o /Path/to/main.o
main.h: // The global variables to be accessed...
#ifndef _main_h
#define _main_h
#include <map>
std::map<int,bool> ArrowKey;
#endif
MKDBControlInterface.h:
#ifndef _MKDBControlInterface_h
#define _MKDBControlInterface_h
#include <map>
#include <GLUT/glut.h>
#include "main.h"
#include "MKDBApplication.h"
class MKDBControlInterface {
public:
MKDBControlInterface( MKDBApplication& App )
: m_App( App )
{
glutSpecialFunc( SpecialListener );
glutSpecialUpFunc( SpecialListenerX );
ArrowKey[GLUT_KEY_LEFT] = false;
ArrowKey[GLUT_KEY_RIGHT] = false;
ArrowKey[GLUT_KEY_UP] = false;
ArrowKey[GLUT_KEY_DOWN] = false;
}
~MKDBControlInterface(){}
void static SpecialListener( int key, int x, int y ){
ArrowKey[key] = true;
}
void static SpecialListenerX( int key, int x, int y ){
ArrowKey[key] = false;
}
private:
MKDBApplication& m_App;
};
#endif
main.cpp
#include "main.h"
#include "MKDBApplication.h"
#include "MKDBControlInterface.h"
#include "MKDBRender.h"
int main( int argc, char *argv[] ){
MKDBApplication App;
MKDBControlInterface Interface( App );
MKDBRender Render( App );
return 0;
}
In main.h you need to declare ArrowKey as
extern "C" std::map<int,bool> ArrowKey;
and in main.cpp after the includes you should define it:
std::map<int,bool> ArrowKey;
BTW, I would also replace #ifndef/#define/#endif with #pragma once in the headers.